user3678624
user3678624

Reputation: 75

Writing generic spring jpa repository for all entities

I am working on Spring Boot application.

We have Service Layer,Rest Controller and Dao as repository.

I have 20 to 30 tables in my database and I dont want to create repository for each entity and extends that to CrudRepository.

ex : User is an Entity, to perform persistance operations on User, I have to create UserRepository which extends CrudRepository.

Same with Department, Company etc...

What i want to do is, I will write a BaseRepository which gonna extend CrudRepository, base repository should accept all entities and do persistance operations.

Is there a way to that ??

Upvotes: 2

Views: 2074

Answers (2)

Johan
Johan

Reputation: 425

I took difference way to handle 'generic' repository access. Instead of creating generic repository, simply just create generic service.

Here is the example on class BaseService :

public abstract class BaseService<T> {

    protected abstract JpaRepository<T, Long> getJpaRepository();

    public T getById(long id) {
        Optional<T> optionalT = getJpaRepository().findById(id);
        return optionalT.orElse(null);
    }

    public T yourAnotherAmazingCustomGenericMethod() {
        ...
    }

}

Here is the example on your service class

@Service
public class MyService extends BaseService<MyEntity> {

    @Autowired
    // !! IMPORTANT : Your repository should implements interface JpaRepository
    private MyEntityRepository myEntityRepository;

    @Override
    protected JpaRepository<MyEntity, Long> getJpaRepository() {
        return myEntityRepository;
    }

    // now this class can access method yourAnotherAmazingCustomGenericMethod() 

}

May someone can make a different approach better than this. :D

Upvotes: 0

John Stringer
John Stringer

Reputation: 587

Don't extend CrudRepository it's functionality is all tied to the generic type, it'd be hacky to extend it for a generic implementation. You probably just want something simple which uses the JPA entity manager directly:

import javax.persistence.EntityManager;

import org.springframework.beans.factory.annotation.Autowired;

public class GenericRepository {

    @Autowired
    private EntityManager entityManager;

    public <T, ID> T findById(Class<T> type, ID id) {
        return entityManager.find(type, id);
    }
}

Upvotes: 2

Related Questions