biniam
biniam

Reputation: 8199

Spring Data JPA/Boot: findBy ... or

I want to write a finder method in my repository to find an object based on one field OR another one while supplying one parameter like:

@RepositoryDefinition(domainClass = Person.class, idClass = Long.class)
public interface PersonRepository extends CrudRepository<Person, Long> {

    List<Person> findAllByIdOrAnotherId(someId);
}

How can I do that without using SQL?

Upvotes: 8

Views: 25897

Answers (2)

Mechkov
Mechkov

Reputation: 4324

One of the cool things about Spring Data JPA is the fact you can define custom queries as abstract methods in your interface.

In a nutshell, you can define a new search criteria just by specifying the @Entity field name you want to query by. So, let's say i want to findAll() by Id and CustomId. Both Id and CustomId are fields on my domain class. I would do:

List<Person> findAllByIdOrCustomId(someId, someCustomId);

For more info, research the link below: Spring Data JPA - DEFINE QUERY METHODS

Upvotes: 0

biniam
biniam

Reputation: 8199

I added a second parameter to the method and it worked.

List<Transaction> findAllByIdOrParentId(Long id, Long parentId);

This is just a definition for the method because I pass the same parameter to the method from the service as:

List<Transaction> transactions = transactionRepository.findAllByIdOrParentId(transactionId, transactionId);

Upvotes: 11

Related Questions