JpaRepository接口继承于PagingAndSortingRespository,使用方法也是和前辈大同小异.(细心的同学应该看出来了,JpaRepository继承于PagingAndSortingRespository,PagingAndSortingRespository继承于CrudRespository,CrudRespository继承于Respository,整个就是一个从上而下的继承树嘛!)
JpaRespository接口下的方法:
List<T> findAll();
List<T> findAll(Sort sort);
List<T> findAll(Iterable<ID> ids);
<S extends T> List<S> save(Iterable<S> entities);
void flush();//执行缓存,与数据库同步;有同学遇到的查询到的结果与数据库不一致的问题,可能就是缓存导致的.
<S extends T> S saveAndFlush(S entity);
void deleteInBatch(Iterable<T> entities);//删除一个实体集合
void deleteAllInBatch();
T getOne(ID id);
方法大都见名知意了,需要提一下的是flush()和deleteInBatch()方法
======================================================================================================================================下面主要讲讲重头戏JpaSpecificationExecutor接口,它是一个单独的接口,现实中也经常使用到它.
使用的它的原因是 在执行分页排序的查询时,可以附加查询条件,增加了灵活性.
通过带查询条件的分页排序查询实例来说明:
1.定义接口(利用多继承,可以实现附加条件的排序_分页查询):
//多继承,使用单独的JpaSpecificationExecutor接口可以丰富查询功能
public interface StudentJpaSpecificationExcutor extends JpaRepository<Student, Integer>
,JpaSpecificationExecutor<Student>{
}
2.测试类进行方法测试
public class StudentJpaSpecificationExcutorTest {
private ApplicationContext ctx = null;
private StudentJpaSpecificationExcutor studentJpaSpecificationExcutor = null;
@Before
public void setUp(){
ctx = new ClassPathXmlApplicationContext("beans.xml");
studentJpaSpecificationExcutor = ctx.getBean(StudentJpaSpecificationExcutor.class);
System.out.println("setup");
}
@After
public void tearDown(){
ctx = null;
System.out.println("teardown");
}
//结合JpaSpecificationExcutor接口
//分页加排序加条件age>23
@Test
public void testPageAndSort(){
System.out.println("start");
Order order = new Order(Direction.ASC,"sage");
Sort sort = new Sort(order);
Pageable pageable = new PageRequest(0,2,sort);
Specification<Student> specification = new Specification<Student>() {
//toPredicate就是查询条件
//root根对象表示实体类,要查询的类型,query所需要添加查询条件,cb构建Predicate
@Override
public Predicate toPredicate(Root<Student> root,CriteriaQuery<?> query,CriteriaBuilder cb) {
// TODO Auto-generated method stub
Path path = root.get("sage");//能获取到Student的sage的路径
return cb.gt(path, 23);
}
};
Page<Student> page = studentJpaSpecificationExcutor.findAll(specification, pageable);
System.out.println("查询的总页数:"+page.getTotalPages());
System.out.println("查询的记录数:"+page.getTotalElements());
System.out.println("查询当前的第几页:"+(page.getNumber()+1));
System.out.println("查询当前页面的集合:"+page.getContent());
System.out.println("查询当前页面的记录数:"+page.getNumberOfElements());
System.out.println("started");
}
}
查询的结果就是大于23岁的,从第一页开始的,每页显示2条的学生信息.
怎么样,是不是很简单呢