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.
This question is related to
java
spring
jpa
spring-data
spring-data-jpa
Yes, that is supported.
Check the documentation provided here 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);
}
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);
you can use the keyword 'In' and pass the List argument. e.g : findByInventoryIdIn
List<AttributeHistory> findByValueIn(List<String> values);
Source: Stackoverflow.com