Adding IN clause List to a JPA Query

JavaJpaJpql

Java Problem Overview


I have built a NamedQuery that looks like this:

@NamedQuery(name = "EventLog.viewDatesInclude",
        query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND "
        + "el.timeMark <= :dateTo AND "
        + "el.name IN (:inclList)")

What I want to do is fill in the parameter :inclList with a list of items instead of one item. For example if I have a new List<String>() { "a", "b", "c" } how do I get that in the :inclList parameter? It only lets me codify one string. For example:

setParameter("inclList", "a") // works

setParameter("inclList", "a, b") // does not work

setParameter("inclList", "'a', 'b'") // does not work

setParameter("inclList", list) // throws an exception

I know I could just build a string and build the whole Query from that, but I wanted to avoid the overhead. Is there a better way of doing this?

Related question: if the List is very large, is there any good way of building query like that?

Java Solutions


Solution 1 - Java

When using IN with a collection-valued parameter you don't need (...):

@NamedQuery(name = "EventLog.viewDatesInclude", 
    query = "SELECT el FROM EventLog el WHERE el.timeMark >= :dateFrom AND " 
    + "el.timeMark <= :dateTo AND " 
    + "el.name IN :inclList") 

Solution 2 - Java

The proper JPA query format would be:

el.name IN :inclList

If you're using an older version of Hibernate as your provider you have to write:

el.name IN (:inclList)

but that is a bug (HHH-5126) (EDIT: which has been resolved by now).

Solution 3 - Java

public List<DealInfo> getDealInfos(List<String> dealIds) {
		String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
		TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
		query.setParameter("inclList", dealIds);
		return query.getResultList();
	}

Works for me with JPA 2, Jboss 7.0.2

Solution 4 - Java

You must convert to List as shown below:

	String[] valores = hierarquia.split(".");		
	List<String> lista =  Arrays.asList(valores);
	
	String jpqlQuery = "SELECT a " +
			"FROM AcessoScr a " +
			"WHERE a.scr IN :param ";
	
	Query query = getEntityManager().createQuery(jpqlQuery, AcessoScr.class);					
	query.setParameter("param", lista);		
	List<AcessoScr> acessos = query.getResultList();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlanObjectView Question on Stackoverflow
Solution 1 - JavaaxtavtView Answer on Stackoverflow
Solution 2 - JavaJose FerrerView Answer on Stackoverflow
Solution 3 - Javauser1114134View Answer on Stackoverflow
Solution 4 - JavaWesley RochaView Answer on Stackoverflow