JPA自定义多条件更新、查询

1、接口层需要继承JpaSpecificationExecutor(maven工程中需要引入spring-boot-starter-data-jpa)
public interface AppManageService extends JpaRepository,JpaSpecificationExecutor {
   @Modifying
   @Transactional
   @Query("update AppModel app set " +
         "app.serviceline = CASE WHEN :#{#appModel.serviceline} IS NULL THEN app.serviceline ELSE :#{#appModel.serviceline} END ," +
         "app.appname = CASE WHEN :#{#appModel.appname} IS NULL THEN app.appname ELSE :#{#appModel.appname} END ," +
         "app.updatetime =  CASE WHEN :#{#appModel.updatetime} IS NULL THEN app.updatetime ELSE :#{#appModel.updatetime} END " +
         "where app.id = :#{#appModel.id}")
   int updateApp(@Param("appModel") AppModel appModel);
}

2、使用方法(builder.like模糊查询,如果精确查询则用builder.equal

@RequestMapping("/findApp")
@ResponseBody
public ResultInfo findApp(@RequestBody AppModel appmodel) {
   ResultInfo resultInfo;
   List allApp;
   try {
      allApp = appManageService.findAll(new Specification(){
         @Override
         public Predicate toPredicate(Root root,
               CriteriaQuery query, CriteriaBuilder builder) {
            Predicate predicate = builder.conjunction();
            List> expressions = predicate.getExpressions();
            if(null != appmodel.getServiceline()){
               expressions.add(builder.like(root.get("serviceline"), "%"+appmodel.getServiceline()+"%"));
            }
            if(null != appmodel.getAppname()){
               expressions.add(builder.like(root.get("appname"), "%"+appmodel.getAppname()+"%"));
            }
            return predicate;
         }
      });
   } catch (Exception e) {
      logger.error("findApp error,cause by " ,e);
      resultInfo = ResultInfo.fail(e.getMessage().toString());
      return resultInfo;
   }
   resultInfo = ResultInfo.success();
   resultInfo.setData(allApp);
   return resultInfo;
}

你可能感兴趣的:(JPA自定义多条件更新、查询)