mobileDev
mobileDev

Reputation: 1464

How to retrieve list of objects by list of fields

Table user has following schema

  id integer PRIMARY KEY,
  name varchar(120) NOT NULL,
  ssn integer NOT NULL

Spring Data JPA provides following in CrudRepository interface to retrieve one user based on id

 Optional<User> findById(Integer id);

But I want to retrieve all User.names,given an list of id's (assume list has no repetions); how can I retrieve their names. I know I can loop the above findById, but that is not practical when table size is very big

Upvotes: 0

Views: 488

Answers (1)

Eklavya
Eklavya

Reputation: 18410

Use findByIdIn for find by the list of ids and get the user list.

List<User> findByIdIn(List<Integer > ids);

And for only get names of users of given ids

@Query(value = "SELECT c.name FROM User c WHERE id IN (?1)")
public List<String> findAllNames(List<Integer> ids);

Upvotes: 2

Related Questions