简体   繁体   English

Hibernate命名查询参数IN列表

[英]Hibernate named query parameter IN list

I have found lots of answers for how to send a list parameter in to a query and check if a value is in that list but I'm trying to do the opposite - pass in the value and check if it's contained in a list in the object. 我已经找到了很多有关如何将list参数发送到查询中并检查值是否在该列表中的答案,但是我正试图做相反的事情-传递值并检查它是否包含在列表中宾语。

I have the following code to try to retrieve a Person using their username. 我有以下代码尝试使用他们的用户名检索一个人。

Person person = uniqueResult(namedQuery(Person.FIND_BY_USERNAME)
    .setParameter("username", username).setMaxResults(1));

The username is contained in a list in the Person object. 用户名包含在Person对象的列表中。

@Column(name = "usernames")
@Convert(converter = PersonUsernameConvertor.class)
private List<String> usernames;

Is it possible to get the Person with the username parameter in their list with a NamedQuery or do I need something else? 是否可以使用NamedQuery在其列表中获取具有username参数的Person或我是否需要其他东西? Below is what I have so far but it's not working, I'm guessing because the parameter value is on the left of the equation. 下面是我到目前为止所拥有的,但是它无法正常工作,我猜是因为参数值位于等式的左侧。

@NamedQuery(name = Person.FIND_BY_USERNAME,
    query = "SELECT p from Person p WHERE :username IN p.usernames)

Example1: 范例1:

@NamedQuery(name = Person.FIND_BY_USERNAME,
query = "SELECT p from Person p WHERE p.usernames in (:username)")

If usernames list contains only John and passing the parameter username with john, the above query works and returns the result. 如果用户名列表仅包含John,并通过john传递参数username,则上面的查询有效并返回结果。

Example2: 范例2:

@NamedQuery(name = Person.FIND_BY_USERNAME,
query = "SELECT p from Person p WHERE p.usernames like CONCAT('%',:username,'%')")

If usernames list contains John,Joe and passing the parameter username with joe,the above query will check the list whether joe exists in the list or not. 如果用户名列表包含John,Joe并使用joe传递参数username,则上面的查询将检查列表中是否存在joe。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM