本人想要实现的效果如下面sql 语句所示:
select * from user u where u.userid like '% 参数1 %' and u.username like '%参数2%'
通过百度已经实现 动态查询代码如下:
public Page getDataForSearch(PageRequest pageRequest, final JSONObject jSONObjSearch) throws SaggException {
Page page = null;
try {
page = userRepo.findAll(new Specification() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder builder) {
List predicates = new ArrayList();
Predicate predicate = null;
Expression namePath = null;
if (null != jSONObjSearch) {
if (StrKit.notBlank(jSONObjSearch.getString("userid"))) {
namePath = root.get("userid");
predicate = builder.like(namePath, "%" + jSONObjSearch.getString("userid") + "%");
predicates.add(predicate);
}
if (StrKit.notBlank(jSONObjSearch.getString("userName"))) {
namePath = root.get("userName");
predicate = builder.like(namePath, "%" + jSONObjSearch.getString("userName") + "%");
predicates.add(predicate);
}
}
query.where(predicates.toArray(new Predicate[predicates.size()]));
return null;
}
}, pageRequest);
} catch (Exception e) {
// 交易人管理模块异常状态码statusCode用2000开始,2001:数据查询错误
throw new SaggException(StatusCodeUtil.personSearchErr);
}
return page;
}
DAO 层代码如下:
public interface UserRepository extends CrudRepository {
// List findAll(Pageable pageable);
Page findAll(Pageable pageable);// 分页需返回page对象
Page findAll(Specification spe, Pageable pageRequest);
Page findByUseridOrUserNameLike(Pageable pageable, String userid, String userName);
问题: 上面这种写法,好像不能达到我期望的效果,上面这个代码哪里错了?怎么改进?请大神赐教,感激不尽……