1、接口层需要继承JpaSpecificationExecutor(maven工程中需要引入spring-boot-starter-data-jpa)
public interface AppManageService extends JpaRepository<AppModel, Integer>,JpaSpecificationExecutor<AppModel> {
@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<AppModel> allApp;
try {
allApp = appManageService.findAll(new Specification<AppModel>(){
@Override
public Predicate toPredicate(Root<AppModel> root,
CriteriaQuery<?> query, CriteriaBuilder builder) {
Predicate predicate = builder.conjunction();
List<Expression<Boolean>> expressions = predicate.getExpressions();
if(null != appmodel.getServiceline()){
expressions.add(builder.like(root.<String>get("serviceline"), "%"+appmodel.getServiceline()+"%"));
}
if(null != appmodel.getAppname()){
expressions.add(builder.like(root.<String>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;
}