使用自定义查询访问Spring

使用自定义查询访问Spring

本文介绍了使用自定义查询访问Spring Repository中的集合字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行查询,以搜索我的应用程序中所有在内容或标签名称上包含关键字但仅公开的关键字的帖子.我正在尝试进行JPQL搜索,但是我不知道如何访问tags.name属性.

I'm trying to make a query to search all Posts from my application containing a keyword on the content or on the tags name but only those who are public. I'm trying to make the JPQL search but I don't know how to access the tags.name property.

注意:Post是具有Tag实体列表的实体;

Note: Post is an entity which has a List of Tag entity;

我已经尝试过了,但是没有用(如我预期的那样):

I have tried this but it's not working (as I expected):

@Query("SELECT p FROM Post p WHERE (p.content LIKE CONCAT('%', LOWER(:keyword),'%' OR p.tags.name LIKE CONCAT('%', LOWER(:keyword)) AND (p.open IS TRUE)")

我看过文档,但没有任何管理方法,什么是最好的方法?

I have looked at the documentation but I don't see any option to manage this, what is the best way to go here?

谢谢!

推荐答案

由于多个tag可以与post关联,因此关系是从PostTag@OneToMany.在这种情况下,join应该可以工作.

Since multiple tags can be associated with a post the relationship is a @OneToMany from Post to Tag. A join should work in this scenario.

尝试一下.

@Query("SELECT p FROM Post p left join p.tags pTags WHERE (p.content LIKE CONCAT('%',LOWER(:keyword),'%' OR pTags.name LIKE CONCAT('%',LOWER(:keyword)) AND (p.open IS TRUE)")

PS :我尚未对此进行测试,但它应该可以工作.

PS : I have not tested this, but it should work.

这篇关于使用自定义查询访问Spring Repository中的集合字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 08:24