To pass a List
(or any Collection
) into a Spring Data JPA repository query, you can use the IN
clause in JPQL or native SQL, and Spring will automatically bind the list elements.
✅ Example 1: Using @Query
with JPQL
@Query("SELECT p FROM Product p WHERE p.id IN :ids")
List<Product> findByIds(@Param("ids") List<Long> ids);
You can then call this method like:
List<Long> ids = Arrays.asList(1L, 2L, 3L);
List<Product> products = productRepository.findByIds(ids);
✅ Example 2: Derived Query Method (No @Query
)
You can even use Spring Data’s method naming:
List<Product> findByIdIn(List<Long> ids);
This does the same thing — it will generate a query like:
SELECT * FROM product WHERE id IN (?, ?, ?)
🧠 Notes:
List
,Set
, or anyCollection
works fine.- Avoid passing a huge list (thousands of items), it might hit SQL limits.
- If your collection is empty, be careful — some databases (like Oracle) may throw errors. You might want to handle the empty case separately.
I’m developing some Spring Apps (most of them sitting on top of Vaadin) – you could check here: https://programtom.com/dev/product-category/technologies/spring-boot-framework/?orderby=date-desc