ChatGPT解决这个技术问题 Extra ChatGPT

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

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.


n
nietaki

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.


Thanks, that was exactly I was looking for. Do they have it documented in CrudRepository page, or discover by reading the code?
It's actually listed in the reference documentation.
Thanks. That "gem is hidden in the appendix B", rightly so :)
Reference docs URL changed
For the method signature: List findByIdIn(List ids); I get the error: Caused by: java.lang.NumberFormatException: For input string: "(1, 2)"
A
Athar

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);

Thanks, this works. Was looking for a "more cleaner" solution i.e without writing the @Query.
Oliver Gierke is the man that would know the answer to this and he has the "more cleaner" solution. You should accept his answer.
Great! I used a Set<String> as a parameter, worked well.
what if I want to pass 2 paramemeters to my method one list and other a normal string , will that work? if yes how shall I name my method
D
Dzinot

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);

}

This works for all interfaces that are extending the CrudRepository interface.
This won't work if the ids size is over 1000 or certain size depending on the DB. How about this? List findByIdIn(List ids, Pageable pageable);