Hibernate重构@Id字段到超类

时间:2017-02-18 00:30:13

标签: java hibernate jpa inheritance orm

有两个不同数据库表的实体类,Table1.java有手动生成ID,Table2.java有序列生成ID,是否可以移动id属性@Id@Column注释,以及吸气剂和放大器id为GenericTable超类的setter,并将@GeneratedValue@SequenceGenerator放在只需要它们的子类中?解决方案必须可以扩展到两种类型的数百个表,并且不应该在两个类中拆分GenericTable超类。

问题是@GeneratedValue仅适用于字段/方法级别,因此必须将其移动到超类,使所有子类都必须实现与@SequenceGenerator特征冲突的Table1.java。 / p>

@Entity
@Table(name = "TABLE1")
public class Table1 extends GenericTable {

  @Id
  @Column(name = "ID", nullable = false, precision = 22, scale = 0)
  private Long id;

  // other properties 
  // getters & setters for id
  // other getters & setters
}

@Entity
@Table(name = "TABLE2")
public class Table2 extends GenericTable {

  @Id
  @GeneratedValue(strategy = SEQUENCE, generator = "generator")
  @SequenceGenerator(name = "generator", sequenceName = "TABLE2_SEQ", allocationSize = 1)
  @Column(name = "ID", nullable = false, precision = 22, scale = 0)
  private Long id;

  // other properties 
  // getters & setters for id
  // other getters & setters
}

@MappedSuperclass
public abstract class GenericTable {

}

1 个答案:

答案 0 :(得分:1)

我认为不可能在一个类中填充这两种配置类型。

我做了一些测试,并且有两个@MappedSuperclass实体,您应该能够实现满足可重用/可扩展需求的解决方案:

基本ID类型父

@MappedSuperclass
public abstract class BasicIdAwareEntity implements Serializable {

    protected Long id;

    @Id
    @Column(name = "ID", nullable = false, precision = 22, scale = 0)
    public Long getId() {
        return id;
    }

序列ID变体父

@MappedSuperclass
public abstract class SequenceIdAwareEntity extends BasicIdAwareEntity {

  @Override
  @Id
  @GeneratedValue(strategy = SEQUENCE, generator = "generator")
  @SequenceGenerator(name = "generator", sequenceName = "TABLE2_SEQ", allocationSize = 1)
  public Long getId() {
     return super.getId();
  }

具体实体

@Entity
@Table(name = "TABLE1")
public class Table1 extends BasicIdAwareEntity {

@Entity
@Table(name = "TABLE2")
public class Table2 extends SequenceIdAwareEntity {

现在,如果您需要在将来的某个时刻重构此映射,例如,您需要更改id列的精度,那么您只需在BasicIdAwareEntity类中进行更改。类型更改也是如此,在良好的IDE的帮助下也应该更改子类。

您需要在所有抽象类中添加的唯一注释是@Id。

如果将来需要为某个表创建不同的生成器,那么只需创建BasicIdAwareEntity的另一个子类。