为了账号安全,请及时绑定邮箱和手机立即绑定

使用 QueryDSL 在两个不同的字段中搜索一个值

使用 QueryDSL 在两个不同的字段中搜索一个值

哆啦的时光机 2022-07-14 10:29:37
我正在使用 Spring Boot 和 QueryDSL 来执行 REST 请求,但是我在执行搜索时遇到问题,该搜索在两个字段中执行具有相同值的查询(澄清一下,如果一个值在一个字段或另一个字段中)。像这样的东西:select * from news where title like '%word%' or content like '%word%';我想做这样的请求(不严格,可能会有所不同):http://localhost?title=word&content=word我的 RestController 中有这个:@GetMappingpublic PagedResources<Resource> get(@QuerydslPredicate(root = News.class) Predicate predicate,                                    @SortDefaults({                                        @SortDefault(sort = "type", direction = ASC),                                        @SortDefault(sort = "dateCreated", direction = DESC)                                    }) Pageable pageable) {    Page<News> pages = newsService.getAllWithPagination(predicate, pageable);    return pagedResourcesAssembler.toResource(pages, newsResourceAssembler);}这是我的存储库:public interface NewsRepository extends JpaRepository<News, Long>, QuerydslPredicateExecutor<News>, QuerydslBinderCustomizer<QNews> {    @Override    default void customize(QuerydslBindings bindings, QNews news) {        bindings.bind(String.class)            .first((SingleValueBinding<StringPath, String>) StringExpression::containsIgnoreCase);}}我厌倦了搜索,我没有找到任何做过类似事情的人。有人对如何做到这一点有任何建议吗?
查看完整描述

2 回答

?
蓝山帝景

TA贡献1843条经验 获得超7个赞

QNews qnews = QNews.news;
final BooleanExpression booleanExpression = qnews.title.like("%word%").or(qnews .content.like("%word%"));

在此之前检查 queryparam 中的空值


查看完整回答
反对 回复 2022-07-14
?
凤凰求蛊

TA贡献1825条经验 获得超4个赞

通过@kumar 的回答和更多的研究,我终于实现了我想要的:


@Override

default void customize(QuerydslBindings bindings, QNews news) {

    bindings.bind(news.title)

        .first((path, value) -> path.likeIgnoreCase("%" + value + "%").or(news.content.likeIgnoreCase("%" + value + "%")));

}


查看完整回答
反对 回复 2022-07-14
  • 2 回答
  • 0 关注
  • 112 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号