【问题标题】:Hibernate / JPA: Is it possible to Override @Id field?Hibernate / JPA:是否可以覆盖 @Id 字段?
【发布时间】:2013-11-14 15:39:33
【问题描述】:

在将@Id分配给父实体中的某个字段后,是否有一种方法可以重新分配子实体中的@Id

例如:

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class Parent implements Serializable {

  @Id
  protected Integer parentId;

  public Integer getId() {
    return parentId;
  }

  public void setId(Integer id) {
    this.id = parentId;
  }
}


@Entity
@Access(AccessType.FIELD)
public class Child extends Parent implements Serializable {

  /*
   What should be added to this entity to re assign the @Id to a new field and 
   make the parentId field just an ordianry field in the Child, not the entity Id
  */
  @Id
  private Long childId;

}

我曾尝试使用@AttributeOverride,但它所能提供的只是重命名 id 列名。

【问题讨论】:

  • 我认为这是不可能的。那么它应该如何映射到RDB? “每个层次结构的单个表”和“每个子类的表”肯定是不可能的。为什么需要这个功能? (顺便说一句:为什么你的孩子继承父类?)
  • @isnot2bad 我有一个通用实体,它包含许多实体之间共享的 id、版本和其他一些字段。并且应用程序已经在构建时考虑了通用实体。但对于一些共享相同字段的新实体,除了 Id 字段类型和名称。但是他们仍然保留旧的 Id 列,但作为一个普通字段

标签: java hibernate jpa


【解决方案1】:

这听起来像是一个设计问题。

实现这一点的正确方法可能是定义另一个类:@MappedSuperclass GenericEntity,其所有属性均为Parent,parentId 除外:

@MappedSuperclass
@Access(AccessType.FIELD)
public abstract class GenericEntity implements Serializable {
     ... all your common attributes without parentId
}

@MappedSuperclass
public abstract class Parent extends GenericEntity implements Serializable {

    @Id
    protected Integer parentId;

    public Integer getId() {
        return parentId;
    }

    public void setId(Integer id) {
        this.id = parentId;
    }

    //nothing more in this class
}

@Entity
public class Child extends GenericEntity implements Serializable {

   @Id
   private Long childId;

   private Integer parentId; //if you need it

   ...
}    

另一种实验性解决方案是在Child 类中隐藏parentId 字段。

免责声明:我不推荐这种方法,我不确定它是否有效!

@Entity
@Access(AccessType.FIELD)
public class Child extends GenericEntity implements Serializable {

   @Id
   private Long childId;

   private Integer parentId;

   ...
}    

【讨论】:

  • 您的第二个解决方案将为孩子添加两个 Id,在引用子实体的其他实体中引发异常,指示我应该为外键分配两列
  • 而对于第一个解决方案,它将导致许多实体中的重构。无论如何,感谢并支持您的努力,但这并不能解决我的主要问题,是否可以重新分配 ID?
【解决方案2】:

您可以通过 xml 覆盖注释元数据: 对于休眠,请参见例如this post

对于一般 JPA,请参见例如this post

【讨论】:

    猜你喜欢
    • 2012-07-01
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2012-01-15
    • 1970-01-01
    相关资源
    最近更新 更多