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

我正在使用 Spring Boot 和 QueryDSL 来执行 REST 请求,但是我在执行搜索时遇到问题,该搜索在两个字段中执行具有相同值的查询(澄清一下,如果一个值在一个字段或另一个字段中)。像这样的东西:


select * from news where title like '%word%' or content like '%word%';

我想做这样的请求(不严格,可能会有所不同):


http://localhost?title=word&content=word

我的 RestController 中有这个:


@GetMapping

public 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);

}

}


我厌倦了搜索,我没有找到任何做过类似事情的人。有人对如何做到这一点有任何建议吗?


哆啦的时光机
浏览 113回答 2
2回答

蓝山帝景

QNews qnews = QNews.news;final BooleanExpression booleanExpression = qnews.title.like("%word%").or(qnews .content.like("%word%"));在此之前检查 queryparam 中的空值

凤凰求蛊

通过@kumar 的回答和更多的研究,我终于实现了我想要的:@Overridedefault void customize(QuerydslBindings bindings, QNews news) {&nbsp; &nbsp; bindings.bind(news.title)&nbsp; &nbsp; &nbsp; &nbsp; .first((path, value) -> path.likeIgnoreCase("%" + value + "%").or(news.content.likeIgnoreCase("%" + value + "%")));}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java