JpaRepository它继承了QueryByExampleExecutor,这个方法里定义了一些用于Example查询的基本方法:
public interface QueryByExampleExecutor<T> {
<S extends T> Optional<S> findOne(Example<S> example);
<S extends T> Iterable<S> findAll(Example<S> example);
<S extends T> Iterable<S> findAll(Example<S> example, Sort sort);
<S extends T> Page<S> findAll(Example<S> example, Pageable pageable);
<S extends T> long count(Example<S> example);
<S extends T> boolean exists(Example<S> example);
}
Example查询翻译过来叫“按例查询(QBE)”。是一种用户界面友好的查询技术。 它允许动态创建查询,并且不需要编写包含字段名称的查询。
Example api由以下三个类组成: 1)Probe: 含有对应字段的实例对象。 2)ExampleMatcher:ExampleMatcher携带有关如何匹配特定字段的详细信息,相当于匹配条件。 3)Example:由Probe和ExampleMatcher组成,用于查询。
Example查询实例
1.在StudentsService中定义使用Example查询的方法。
public interface StudentsService {
List<Students> findAll(Example<Students> example);
}
2.在StudentsServiceImpl中调用QueryByExampleExecutor接口的findAll方法。
@Service
public class StudentsServiceImpl implements StudentsService {
@Resource
private StudentsRepository studentsRepository;
@Override
public List<Students> findAll(Example<Students> example) {
return studentsRepository.findAll(example);
}
}
3.编写测试类,测试Example查询。
@RunWith(SpringRunner.class)//指定Junit4使用Spring提供的测试环境
@SpringBootTest
public class StudentsServiceTest {
@Resource
private StudentsService studentsService;
@Test
public void testQueryStudentsWithExample(){
Students s = new Students();
s.setSname("张");
s.setGender("男");
s.setSchool("四川大学");
s.setMajor("计算机科学与技术");
ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("sname",ExampleMatcher.GenericPropertyMatchers.startsWith())
.withIgnorePaths("sid").withIgnorePaths("cid").withIgnorePaths("status")
.withIgnorePaths("birthday").withIgnorePaths("version").withIgnorePaths("flag")
.withIgnorePaths("create_time").withIgnorePaths("modify_time");
Example<Students> example = Example.of(s ,matcher);
List<Students> studentsList= studentsService.findAll(example);
for(Students stu : studentsList){
System.out.println(stu);
}
}
}
小结: 1).通过在使用Springdata jpa时可以通过Example来快速的实现动态查询,同时配合Pageable可以实现快速的分页查询功能。 2).对于非字符串属性的只能精确匹配,比如想查询在某个时间段内注册的用户信息,就不能通过Example来查询。