srekh
srekh

Reputation: 21

Is it possible to use one common repository for different entities in Spring data JPA

For example, I have entities like Car, Person, Customer. I need generic method like findBy using Specification in my repository class. I do not want to write different repository for each of the entities. Is it possible to create one common repository for all the entities and use it in my application. How to create the instance of the repository with different entity types. I am currently using spring boot for my testing

Upvotes: 1

Views: 3733

Answers (1)

manish
manish

Reputation: 20135

If your code is structured as:

@MappedSuperclass class AbstractEntity implements Serializable {}

@Entity class Car      extends AbstractEntity {}

@Entity class Person   extends AbstractEntity {}

@Entity class Customer extends AbstractEntity {}

you can do this:

@NoRepositoryBean interface AbstractEntityRepository<T extends AbstractEntity>
                            extends JpaRepository<T, ...>
                                    , JpaSpecificationExecutor<T> {}

interface CarRepository extends AbstractEntityRepository<Car> {}

interface PersonRepository extends AbstractEntityRepository<Person> {}

interface CustomerRepository extends AbstractEntityRepository<Customer> {}

This will give you access to methods that take a Specification<EntityType> on all your repositories through JpaSpecificationExecutor.

Upvotes: 2

Related Questions