2

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.

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.

@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? 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)

1 Answer 1

2

Example1:

@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.

Example2:

@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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.