如何使用 MapperSuperClass 在 Spring Data JPA 中实现数据库继承?

How to implement database inheritance in Spring Data JPA with MapperSuperClass?

我正在 Spring Data JPA 中尝试 JOINED 类型的数据库继承,参考 this article。这很好用。但我必须在我的项目中实施 MappedSuperClass 。我已经通过以下方式实施:

Base.java

@MappedSuperclass
public abstract class Base {
    public abstract Long getId();
    public abstract void setId(Long id);
    public abstract String getFirstName();
    public abstract void setFirstName(String firstName);
}

BaseImpl.java

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class BaseImpl extends Base {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String firstName;

    ...
}

Super1.java

@MappedSuperclass
public abstract class Super1 extends BaseImpl {
    public abstract String getSuperName();
    public abstract void setSuperName(String guideName);
}

Super1Impl.java

@Entity
public class Super1Impl extends Super1 {
    private String superName;

    ...
}

BaseBaseRepository.java

@NoRepositoryBean
public interface BaseBaseRepository<T extends Base> extends JpaRepository<T, Long> { }

BaseRepository.java

@NoRepositoryBean
public interface BaseRepository<T extends Base> extends BaseBaseRepository<Base> { }

BaseRepositoryImpl.java

@Transactional
public interface BaseRepositoryImpl extends BaseRepository<BaseImpl> { }

Super1Repository.java

@NoRepositoryBean
public interface Super1Repository<T extends Super1> extends BaseBaseRepository<Super1> { }

Super1RepositoryImpl.java

@Transactional
public interface Super1RepositoryImpl extends Super1Repository<Super1Impl> {  }

我正在尝试在测试用例中保存一个 Super1 对象:

@Test
public void contextLoads() {
    Super1 super1 = new Super1Impl();
    super1.setSuperName("guide1");
    super1.setFirstName("Mamatha");
    super1.setEmail("jhhj");
    super1.setLastName("kkjkjhjk");
    super1.setPassword("jhjjh");
    super1.setPhoneNumber("76876876");

    System.out.println(super1Repository.save(super1));
}

但我收到以下错误:

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'baseRepositoryImpl':
    Invocation of init method failed; nested exception is java.lang.IllegalArgumentException:
      This class [class com.example.entity.Base] does not define an IdClass
.....
Caused by: java.lang.IllegalArgumentException: This class [class com.example.entity.Base] does not define an IdClass
.......

Super1Impl 中尝试了 @PrimaryKeyJoinColumn(name = "id", referencedColumnName = "id"),但仍然出现相同的错误。

错误是由不正确的存储库接口声明引起的。

BaseRepository<T extends Base> extends BaseBaseRepository<Base>

应该是

BaseRepository<T extends Base> extends BaseBaseRepository<T>

Super1Repository<T extends Super1> extends BaseBaseRepository<Super1>

应该是

Super1Repository<T extends Super1> extends BaseBaseRepository<T>

如当前声明的那样,BaseBaseRepository<Base> 表示 Base 个对象的存储库,并且 Base 没有 @Id 字段,因此出现错误。