Spring CrudRepository findByInventoryIds(List<Long> inventoryIdList) - equivalent to IN clause

JavaSpringJpaSpring DataSpring Data-Jpa

Java Problem Overview


In Spring CrudRepository, do we have support for "IN clause" for a field? ie something similar to the following?

 findByInventoryIds(List<Long> inventoryIdList) 

If such support is not available, what elegant options can be considered? Firing queries for each id may not be optimal.

Java Solutions


Solution 1 - Java

findByInventoryIdIn(List<Long> inventoryIdList) should do the trick.

The HTTP request parameter format would be like so:

Yes ?id=1,2,3
No  ?id=1&id=2&id=3

The complete list of JPA repository keywords can be found in the current documentation listing. It shows that IsIn is equivalent – if you prefer the verb for readability – and that JPA also supports NotIn and IsNotIn.

Solution 2 - Java

For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:

@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);

Solution 3 - Java

Yes, that is supported.

Check the documentation provided [here][1] for the supported keywords inside method names.

You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:

List<Inventory> findByIdIn(List<Long> ids);

I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:

The Entity

@Entity
public class Inventory implements Serializable {

  private static final long serialVersionUID = 1L;

  private Long id;

  // other fields
  // getters/setters

}

The Repository

@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {

  List<Inventory> findByIdIn(List<Long> ids);

}

[1]: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation "here"

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
QuestionEspressoView Question on Stackoverflow
Solution 1 - JavaOliver DrotbohmView Answer on Stackoverflow
Solution 2 - JavadigitaljoelView Answer on Stackoverflow
Solution 3 - JavaDzinotView Answer on Stackoverflow