geffchang
geffchang

Reputation: 3340

How do I get a distinct list of objects with JpaRepository.findAll using a Predicate?

I have something like:

Predicate p = ...;
List<MyObject> objectList = (List<MyObject>) myRepository.findAll(p); // myRepository is autowired

This gets the list of all MyObjects, with duplicates. Is it possible to get a DISTINCT list instead?

Do I really need to use an EntityManager and CriteriaBuilder? Or can it be done with just the predicate and the repository object?

I'm not talking about iterating through the list manually and removing duplicates, or using any Collections API, but more on JPA or QueryDSL API.

Upvotes: 1

Views: 1416

Answers (1)

Algorithmist
Algorithmist

Reputation: 6695

Yes It is possible.Below are the simple steps that I can think of

  • Implement hashCode() and equals() in your MyObject Class.

  • Create a Set based on your above list using its constructor directly which takes a Collection as an argument.

Upvotes: 1

Related Questions