Spring Data JPA学习

1,自定义的repository 需要继承这2个接口


public interface AdviceClassRepository extends JpaRepository<AdviceClass,Long>,JpaSpecificationExecutor<AdviceClass> {
   
}
JpaRepository作用:支持基本的增删改查和排序功能
JpaSpecificationExecutor作用:支持自定义查询和分页及排序
下面2个示例 展示自定义查询
public Page<AdviceClass> findAll(AdviceClass adviceClass, PageRequest pageRequest) {
/*Sort sort = new Sort(Sort.Direction.ASC, "orderNumber","id");//这里是用POJO的属性,不是表里面*/
// Pageable pageable = new PageRequest(pageRequest.getPageNumber(),pageRequest.getPageSize(), new Sort(Sort.Direction.ASC, new String[]{"orderNumber"}));
return adviceClassRepository.findAll(Specifications.where(new Specification<AdviceClass>() {
@Override
public Predicate toPredicate(Root<AdviceClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate=cb.conjunction();
if(adviceClass!=null){
if(StringUtils.isNotBlank(adviceClass.getAdviceName())){
predicate.getExpressions().add(cb.like(root.<String>get("adviceName"),"%"+StringUtils.trim(adviceClass.getAdviceName())+"%"));
}
if(adviceClass.getActive()!=null){
predicate.getExpressions().add(cb.equal(root.<Short>get("active"), adviceClass.getActive()));
}
if(StringUtils.isNotBlank(adviceClass.getRemark())){
predicate.getExpressions().add(cb.like(root.<String>get("remark"),"%"+StringUtils.trim(adviceClass.getRemark())+"%"));
}
}
return predicate;
}
}),pageRequest);

}
//注意下pageRequest的分页对象,第一页是page=0
Page<User> findAll(name,age,pn,ps){
  dao.findAll(Specifications.where(getWhereClause(name,age)),
  new PageRequest(pn-1,ps));
}

private Specification<User> getWhereClause(name,age) {
  return new Specification<User>() {
    @Override
    public Predicate toPredicate(Root<User> r, CriteriaQuery<?> q, CriteriaBuilder cb) {
    Predicate predicate = cb.conjunction();
       if (StringUtils.isNotBlank(name)) {
         predicate.getExpressions().add(
           cb.like(r.<String>get("name"), "%" + StringUtils.trim(name) + "%")
         );
       }
       ...
       return predicate;
    }
  };
}

 不过推荐用下面的分页方法,代码整洁 简单:


 public Page<Info> findPageListByName(String name){
String sql="SELECT * FROM info WHERE `name` LIKE '%"+name+"%'";
int count=jdbcTemplate.query(sql, Mapper.Info_MAPPER).size();
     Pageable pageable=new PageRequest(0,2);//这个0表示第一个,2表示查询2条记录(mysql 索引是从0开始)
        List<Info> list=jdbcTemplate.query(sql+" limit "+pageable.getPageNumber()+","+pageable.getPageSize(), Mapper.Info_MAPPER);//这个就需要带上分页条件

return new PageImpl<Info>(list,pageable,count);
}
 

 介绍下Springdata 动态查询:

首先repository继承 JpaRepository

然后使用Example实例;参考下面方法

@Bean
    public CommandLineRunner demo2(ERepository repository){
        return (args) ->{
            Employee e=new Employee();
            ExampleMatcher matcher = ExampleMatcher.matching()
                    .withIgnorePaths("lastname");
            e.setName("Jack");
            Example<Employee> example=Example.of(e,matcher);
            log.info("-------------------------------");
            List<Employee> list=repository.findAll(example);
            for (Employee employee : list) {
                log.info(employee.toString());
            }
            log.info("");
        };
    }

该示例中,Employee对象中只有name属性会当成查询的条件(只对name赋值了)

Example中也可以只接收一个实体对象的方法,如:Example.of(e);


原文地址:https://www.cnblogs.com/dwb91/p/6555746.html