Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jpa named query : named bind variables for list

Tags:

java

sql

jpa

if you have a namedquery with a list like :

@NamedQuery(name="selection" , query=" SELECT x FROM Employee x WHERE x.name IN ('Jack', 'Jill')")

is it possible to make the list to named bind variables so you set what you want with :

q.setParameter( .......  );

Any suggestions would be welcome

like image 658
Darth Blue Ray Avatar asked Dec 26 '12 13:12

Darth Blue Ray


People also ask

How do I use the same parameter multiple times in my query using JPA?

If for some reason we do need to use the same parameter many times within the same query, we just need to set it once by issuing the “setParameter” method. At runtime, the specified values will replace each occurrence of the parameter.

What is the difference between JPQL and native query?

JPQL is the most commonly used query language with JPA and Hibernate. It provides an easy way to query data from the database. But it supports only a small subset of the SQL standard, and it also does not support database-specific features. If you want to use any of these features, you need to use a native SQL query.

What is NamedQuery?

A named query is a SQL expression represented as a table. In a named query, you can specify an SQL expression to select rows and columns returned from one or more tables in one or more data sources.


2 Answers

Yes, it's possible. Just do it like for any other parameter:

@NamedQuery(name="selection" , query=" SELECT x FROM Employee x WHERE x.name IN :names")

q.setParameter("names", Arrays.asList("Jack", "Jill"));
like image 116
JB Nizet Avatar answered Oct 03 '22 19:10

JB Nizet


Use this way

@NamedQuery(name="selection" , query=" SELECT x FROM Employee x WHERE x.name IN (:availableCollection)") 


namesCollection // conatains your Lsit of names

query.setParameterList('availableCollection', namesCollection);
like image 27
NPKR Avatar answered Oct 03 '22 18:10

NPKR