一般简单的查询,可以使用,findByName,findById等方法,但是当这种方法越来越多的时候,就会显得特别冗杂,这个时候就需要把方法进行合并,spring data jpa提供了一种Query by Example的方法。
@Override
public Page queryByPage(T t, Pageable pageable) {
Example example = Example.of(t);
return baseDao.findAll(example, pageable);
}
这种查询会将实体中所有不为空的属性(包括父类的)都作为查询条件
SELECT roleentity0_.id AS id1_7_, roleentity0_.delete_flag AS delete_f2_7_, roleentity0_.system_id AS system_i3_7_, roleentity0_.create_time AS create_t4_7_, roleentity0_.create_user_id AS create_u5_7_, roleentity0_.update_time AS update_t6_7_, roleentity0_.update_user AS update_u7_7_, roleentity0_.content AS content8_7_, roleentity0_.org_id AS org_id9_7_, roleentity0_.role_name AS role_na10_7_, roleentity0_.role_type AS role_ty11_7_, roleentity0_.weight AS weight12_7_
FROM dafangzi_role roleentity0_
WHERE roleentity0_.update_time=? AND roleentity0_.create_time=? AND roleentity0_.delete_flag=?
ORDER BY roleentity0_.update_time DESC
LIMIT ?
@Override
public Page queryByPage(T t, Pageable pageable) {
//Example example = Example.of(t);
ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("createTime", "updateTime");
Example example = Example.of(t, matcher);
return baseDao.findAll(example, pageable);
}
再查看查询结果,就是我们想要的结果了
SELECT roleentity0_.id AS id1_7_, roleentity0_.delete_flag AS delete_f2_7_, roleentity0_.system_id AS system_i3_7_, roleentity0_.create_time AS create_t4_7_, roleentity0_.create_user_id AS create_u5_7_, roleentity0_.update_time AS update_t6_7_, roleentity0_.update_user AS update_u7_7_, roleentity0_.content AS content8_7_, roleentity0_.org_id AS org_id9_7_, roleentity0_.role_name AS role_na10_7_, roleentity0_.role_type AS role_ty11_7_, roleentity0_.weight AS weight12_7_
FROM dafangzi_role roleentity0_
WHERE roleentity0_.delete_flag=?
ORDER BY roleentity0_.update_time DESC
LIMIT ?
ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("createTime", "updateTime").withMatcher("roleName", match -> match.contains());
Example example = Example.of(roleEntity, matcher);
Page entityPage = roleService.queryByPage(example, PageRequest.of(page-1, limit, sort));
这样,就变成模糊查询了
SELECT roleentity0_.id AS id1_7_, roleentity0_.delete_flag AS delete_f2_7_, roleentity0_.system_id AS system_i3_7_, roleentity0_.create_time AS create_t4_7_, roleentity0_.create_user_id AS create_u5_7_, roleentity0_.update_time AS update_t6_7_, roleentity0_.update_user AS update_u7_7_, roleentity0_.content AS content8_7_, roleentity0_.org_id AS org_id9_7_, roleentity0_.role_name AS role_na10_7_, roleentity0_.role_type AS role_ty11_7_, roleentity0_.weight AS weight12_7_
FROM dafangzi_role roleentity0_
WHERE (roleentity0_.role_name LIKE ?) AND roleentity0_.delete_flag=?
ORDER BY roleentity0_.update_time DESC
LIMIT ?
附其它字符串处理的操作
参考链接:https://docs.spring.io/spring-data/jpa/docs/current/reference/html/
更多有趣,好玩的信息请关注我的微信公众号!
`