【问题标题】:How to inherit and replace a @Entity from commons package?如何从 commons 包继承和替换 @Entity?
【发布时间】:2020-12-10 09:49:40
【问题描述】:

我在公共包中有一个@Entity

@Entity("person")
public class Person {
    //fields...
}

在一个实现应用程序中,我想用一些自定义字段来扩展这个实体。 但是我还是想映射到表person

@Entity("person")
public class Person extends org.commons.Person {
    //additional fields
}

结果:

Caused by: org.hibernate.DuplicateMappingException: The [Person] and [CustomPerson] entities 
share the same JPA entity name: [person] which is not allowed

那么我如何扩展该实体并告诉 spring 以某种方式“忘记”父 Person 实体,以便只加载我的 CustomPerson

【问题讨论】:

  • 只需使用不同的实体名称。你为什么要把它命名为和父类一样呢?
  • 不是一个答案,但是:我会在这里违反 DRY 原则,只是从 commons 复制课程。原因很简单,如果 commons 中的实体发生变化,这可能不受您的控制,您的自定义人员实体可能会中断。这可能就像重命名 @Column 中的字段一样简单。

标签: java spring hibernate spring-data-jpa spring-data


【解决方案1】:

问题是您为两个实体分配了相同的名称。 You don't need to do that。您可以使用 @Entity、@Table 和 @Inheritance(默认情况下使用单表继承)来注释父实体,而只需使用 @Entity 来注释子类实体:

@Entity
@Table("person")
@Inheritance
public class Person {
    //fields...
}
@Entity
public class CustomPerson extends Person {
    //additional fields
}

【讨论】:

  • 我认为目标表名将来自 @Entity 注释,因此需要同名。
  • 今天回到这个,发现@Inheritance甚至不需要继承表名。
猜你喜欢
  • 2012-03-24
  • 1970-01-01
  • 2014-06-05
  • 2011-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-19
相关资源
最近更新 更多