JpaRepository of abstract @MappedSuperclass without @Id

Viewed 3498

I have an abstract entity annotated with @MappedSuperclass:

@MappedSuperclass
public abstract class BaseEntity {
    public abstract T getId();
    public abstract void setId(T id);
}

Then I inherit my Entities from it, defining their id in each one:

@Entity
public class EntityA {
  @Id
  private int id;
  // ....
}

@Entity
public class EntityB {
  @Id
  private long id;
  // ....
}

Now I want to create a generic JpaRepository that accepts any class that extends from my Base Entity:

public interface BaseRepository<T extends BaseEntity, ID extends Serializable> extends JpaRepository<T, ID> {
}

But Spring trows an exception saying BaseEntity has no ID:

java.lang.IllegalArgumentException: This class [BaseEntity] does not define an IdClass

Please, check Plog's comments in his answer. I could solve it injecting each repository type in service's contructor

1 Answers

As far as I know you can't make generic repositories like this. You will need to make an individual repository for each of your concrete entity classes. aggregate roots (thanks @JensSchauder).

You can however make a generic base repository that can define some common queries between these two repositories by marking it as a @NoRepositoryBean:

@NoRepositoryBean
public interface BaseRepository<T extends BaseEntity, ID extends Serializable> extends JpaRepository<T, ID> {
  //common methods
}

Your concrete class repositories should then extend this instead of JpaRepository:

public interface EntityARepository extends BaseRepository<EntityA, Integer> {
}
Related