本文只简单介绍精确匹配(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))); } } }