User user =newUser();
user.setUsername("admin");//将匹配对象封装成Example对象
Example<User> example = Example.of(user);//根据条件精准匹配对象
List<User> list = userRepository.findAll(example);
System.out.println(list);
备注:使用Example查询,默认情况下会忽略空值
3、自定义匹配器规则
User user =newUser();
user.setUsername("y");
user.setAddress("sh");
user.setPassword("admin");//创建匹配器
ExampleMatcher matcher = ExampleMatcher.matching()//模糊查询匹配开头,即{username}%.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.startsWith())//模糊查询匹配结尾,即%{username}//.withMatcher("username", ExampleMatcher.GenericPropertyMatchers.endsWith())//全部模糊查询,即%{address}%.withMatcher("address", ExampleMatcher.GenericPropertyMatchers.contains())//字段不参与匹配,即不管password是什么值都不加入查询条件.withIgnorePaths("password");//将匹配对象封装成Example对象
Example<User> example = Example.of(user, matcher);//根据条件查询
List<User> list = userRepository.findAll(example);
System.out.println(list);
文章目录Spring Data JPA Example基本使用实例1、创建实体映射2、根据条件精准匹配3、自定义匹配器规则Spring Data JPA Example基本使用实例1、创建实体映射@Entity@Table(name="tb_user")@Data@AllArgsConstructor@NoArgsConstructor@ToStringpublic class User { @Id @GeneratedValue(strategy = Generatio