how do i create a generic repository?

I see a lot of issues with what you’re trying to do here. Remember, when Spring initializes it’s going to look for a bean of the type you’ve declared to inject. To do this, it needs to be a resolvable type, see

The spring data jpa repositories are already generic, you can extend this

public interface MyRepository<T> extends CrudRepository<T, Long>{}

public interface TheirRepository<T> extends MyRepository<T>{}

public interface AnotherRepository<T> extends TheirRepository<T>{}

as far as you want, but ultimately if you want to use it you’ll have to declare one that conforms to your entity. So, no matter how you dice this, you’re going to end up with having to declare something like

public interface MyGenericRepository<MyActualEntity>{}

To get away from this, I encourage you to go ahead and create all your repositories as you normally would, then make a service class that generically saves, updates, deletes the entities by looking up the repository for the type that your operating on. Something like this:

import org.springframework.stereotype.Service;
import org.springframework.web.context.WebApplicationContext;

public class GenericPersistenceService {

  private final WebApplicationContext applicationContext;
  private Repositories repositories;

  public GenericPersistenceService(WebApplicationContext applicationContext) {
    repositories = new Repositories(applicationContext);
    this.applicationContext = applicationContext;

  public <T> T save(T object) {
    Object repository = repositories.getRepositoryFor(object.getClass()).orElseThrow(
        () -> new IllegalStateException(
            "Can't find repository for entity of type " + object.getClass()));
    CrudRepository<T, Long> crudRepository = (CrudRepository<T, Long>) repository;


The repositories are populated when the service is created, then when you pass an entity to the save method, it looks up the repository for the given entity and performs the save operation.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top