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



我正在尝试在Spring Data JPA中使用类型JOINED的数据库继承,引用本文。这很好。但是我已经在项目中实现了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> { }

baseerepository.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字段,因此错误。

相关内容

  • 没有找到相关文章

最新更新