Home > Database > Mysql Tutorial > Can JPQL's IN Clause Handle Collections Directly?

Can JPQL's IN Clause Handle Collections Directly?

Susan Sarandon
Release: 2024-12-28 19:06:11
Original
993 people have browsed it

Can JPQL's IN Clause Handle Collections Directly?

JPQL IN Clause: Unrolling Arrays, Lists, and Other Collections

In Java Persistence Query Language (JPQL), the IN clause allows you to specify a list of specific values for comparison. However, if you need to compare a collection of values instead of listing them out individually, you might wonder if there's a way to do it in JPQL.

Answer:

Yes, in JPA 2.0 and later, you can specify a Collection in the IN clause to be unrolled to its individual values. To do this:

  1. Define the JPQL Query: Create a JPQL query with the IN clause and a named parameter, for example:
String qlString = "select item from Item item where item.name IN :names";
Copy after login
  1. Create a Collection: Create a Java Collection (e.g., a List or Set) containing the values you want to check against.
  2. Set the Parameter: Use the setParameter() method on the Query object to pass the Collection as the value for the named parameter:
Query q = em.createQuery(qlString, Item.class);
List<String> names = Arrays.asList("foo", "bar");
q.setParameter("names", names);
Copy after login

Example:

The following example in EclipseLink retrieves all Item objects whose names match either "foo" or "bar":

String qlString = "select item from Item item where item.name IN :names";
Query q = em.createQuery(qlString, Item.class);

List names = Arrays.asList("foo", "bar");

q.setParameter("names", names);
List actual = q.getResultList();

assertNotNull(actual);
assertEquals(2, actual.size());
Copy after login

Note for Hibernate:

Prior to Hibernate 4, you need to surround the parameter in parentheses in the JPQL query:

String qlString = "select item from Item item where item.name IN (:names)";
Copy after login

However, this is a Hibernate-specific extension and is not part of the standard JPQL syntax.

The above is the detailed content of Can JPQL's IN Clause Handle Collections Directly?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template