Appending custom conditions on spring data jpa repository method queries

Viewed 13093

Short Version

I am looking for a way to have all the findBy methods of a repository class appended with a particular condition

Full Version

Let's assume I have a Product entity and Customer entity. Both of them extends the OwnerAwareEntity and they inherit ownerRef field which identifies the owner of the entity( It could be a merchant or a partner ). I want to have the findBy methods of the Product and Customer modified in runtime such that they are appended with an additional condition of the ownerRef. The ownerRef value could be identified from the user session.

Example

The parent entity class that provides the common ownerRef field

public class OwnerAwareEntity implements Serializable {

 private String ownerRef;

}

Customer entity extending OwnerAwareEntity

public class Customer extends OwnerAwareEntity {

  private String firstname;

  private String mobile ;

}

Product entity extending OwnerAwareEntity

public class Product extends OwnerAwareEntity {

  private String code;

  private String name;

}

Repository class for Product & Customer extending an OwnerAwareRepository

public interface OwnerAwareRepository extends JpaRepository {

}

public interface ProductRepository extends OwnerAwareRepository {

  Product findByCode(String code );

}

public interface CustomerRepository extends OwnerAwareRepository {

  Customer findByFirstname(String firstname );

}

This, when executed, should result in a query like below

select P from Product P where P.code=?1 and P.ownerRef='aValue'
&
select C from Customer C where C.firstname=?1 and C.ownerRef='aValue'

What should be my approach to have this appending of condition achieved?. I only want this appending to be happening when the parent repository is OwnerAwareRepository.

2 Answers
Related