本文只簡單介紹精確匹配(sql中 'where ** = **')、字符串搜索(sql中'where ** like %name%')。java
若是須要更多高級應用,能夠參考spring jpa官方示例,傳送門。git
一.準備工做github
1.建立一個標準的spring boot jpa程序,並配置數據庫鏈接spring
pom.xmlsql
... <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ...
2.實體類 User.java數據庫
... @Entity public class User { @Id @GeneratedValue private Integer id; private String name; private Short type; @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", type=" + type + '}'; } //... setter / getter.. }
3.Repository UserRepository.javaide
... import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository extends JpaRepository<User, Integer> {}
二.測試程序 UserService.java ,運行 Application 便可看到結果spring-boot
@Component @Transactional public class UserService { private final UserRepository userRepository; private Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired public UserService(UserRepository userRepository) { this.userRepository = userRepository; //初始化數據 init(); //測試查新 printAll("經過 Example 精確查找數據", queryByExample()); printAll("經過 Example 字符串匹配", queryByExampleMatcher()); } Collection<User> queryByExample() { User user = new User(); user.setType((short) 1); Example<User> userExample = Example.of(user); return userRepository.findAll(userExample); } Collection<User> queryByExampleMatcher() { User user = new User(); user.setName("10010"); Example<User> userExample = Example.of(user, ExampleMatcher.matching().withMatcher("name", /*startsWith -> 10010% * endsWith -> %10010 * contains -> %10010% * */ ExampleMatcher.GenericPropertyMatchers.startsWith())); return userRepository.findAll(userExample); } void printAll(String pre, Collection<User> userIterator) { logger.info("遍歷 用戶列表 {}", pre); for (User u : userIterator) { logger.info(u.toString()); } } void init() { for (int i = 0; i < 443; i++) { userRepository.save(new User(("100" + i + "00111" + i), (short) (i % 3))); } } }