简体   繁体   中英

JPA JPQL IN clause: How to use IN clause in JPA?

@Query("SELECT al FROM Customer al WHERE al.companyCode = ?1 AND al.fileCode IN ?2")

List findallByGroup(int CompanyCode, String groups);

Or

@Query("SELECT al FROM Customer al WHERE al.companyCode = :CompanyCode AND al.fileCode IN :groups")

List<Customer> findallByGroup(@Param("CompanyCode") int CompanyCode,@Param("groups") List<BigInteger> groups);

OR

@Query("SELECT al FROM Customer al WHERE al.companyCode = :CompanyCode AND al.fileCode IN (:groups)")

List<Customer> findallByGroup(@Param("CompanyCode") int CompanyCode,@Param("groups") List<BigInteger> groups);
findAllByCompanyCodeAndFileCodeIn(int CompanyCode, List<String> groups)

You don't need @Query . Spring data can understand the query from method name. Use the above method.

Not directly related to OP's specific query, but relevant to JPA IN clause in general:

Contrary to pvpkiran's answer, if you are doing anything other than SELECT queries (eg DELETE, UPDATE), it may be much more efficient to use @Query :

@Modifying
@Query("DELETE from Customer al where al.fileCode in :groups")
deleteByFileCodeIn(@Param("groups") List<String> groups)

instead of relying on Spring JPA's query method:

deleteByFileCodeIn(List<String> groups) // avoid this

Reason:

Spring JPA query method's default implementation of the IN clause is inefficient. Underneath the hood, it will 1. first select all records that match the IN criteria, then 2. execute a DELETE statement for each record found.

select customer.id as id,... from customer where customer.file_code in (?,?,?,...)
delete from customer where id=?
delete from customer where id=?
delete from customer where id=?
...

This means that if there are 1000 matching records, it will generate and execute 1000 delete statements -- instead of a single DELETE...IN statement which is what's usually intended.

By using @Query for IN clauses, you can override Spring JPA's default implementation and dictate a more efficient query to use instead. In my own testing this has resulted in 10x improvement in response time for large (>3K) datasets.

One caveat is that depending on the database, there may be limitations in the number of parameters that can be used in the IN clause. This can be overcome by partitioning the List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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