这里都是我开发过程中遇到困难后总结出来的spring boot和jpa相关的常用知识点。写这个是为了方便以后再用到相关知识点时能很方便的运用,希望帮助我自己的同时也能帮助到你。
jpa知识点- 1,添加数据时,自动添加时间
- 2,jpa实现复杂和分页查询
下面是细节
1-1:添加数据时,自动添加时间
1,在数据库中的表格对应的bean /** * 创建时间 */ @CreatedDate @Temporal(TemporalType.TIMESTAMP)// 格式年月日时分秒 private Date createTime; /** * 修改时间 */ @LastModifiedDate @Temporal(TemporalType.TIMESTAMP) private Date modifyTime; 2.实体类头加注解 @EntityListeners(AuditingEntityListener.class) 3.SpringBoot启动类加注解 @EnableJpaAuditing
2-2:jpa实现复杂和分页查询
//1,实现JpaSpecificationExecutor接口 public interface RunOrderRepository extends JpaRepository<RunOrder, String>,JpaSpecificationExecutor<RunOrder> {} //2,在service中做以下处理即可: public Page<RunOrder> canRobbedOrders(PageRequest pageable) { //查询条件构造 Specification<RunOrder> spec = (Specification<RunOrder>) (root, query, cb) -> { Predicate p3 = cb.equal(root.get("orderStatus"), 0);//只查询订单状态为0的订单 return cb.and(p3); // 下面方式使用JPA的API设置了查询条件,所以不需要再返回查询条件Predicate给Spring Data Jpa,故最后return null;即可。 //query.where(p); //return null; }; //依据updateTime做到排序 Sort sort = new Sort(Sort.Direction.DESC, "updateTime"); //实现分页 PageRequest pageable = new PageRequest(page, size, sort); return repository.findAll(spec, pageable); }持续更新中。。。。