【问题标题】:Heritage of id in hibernatehibernate中id的继承
【发布时间】:2015-08-20 06:55:15
【问题描述】:

我在 BD 中有 MOBILE 和 VESSEL 表。他们之间有传承的关系。 MOBILE 是父节点,VESSEL 有一个外键来拥有相同的 id。

在 Java 中我有 2 个类:

@Entity
public class Mobile implements Serializable, ITechnicalBO {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id")
    private Vessel vessel;

{.................}

}


@Entity
public class Vessel implements java.io.Serializable, ITechnicalBO {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id")
    private Mobile mobile;

{.................}

}

我需要很好地声明 id。我在互联网上找到了很多类似的主题,但我无法解决我的问题。

我如何真正向 Hibernate 声明必须生成 VESSEL 的 id 并分配 MOBILE 的 id 的 id?

感谢您的帮助。

【问题讨论】:

    标签: java hibernate inheritance


    【解决方案1】:

    你说 Mobile 是父级,所以 Vessel 应该扩展 Mobile:

    @Entity
    @PrimaryKeyJoinColumn(name = "id_vessel", referencedColumnName = "id_mobile")
    public class Vessel extends Mobile implements java.io.Serializable {
    
        @Column(name="id_vessel", insertable =  false, updatable = false)
        private Integer id;
        // Vessel inherits all the fields from Mobile. You can add some if you want.
    }
    
    @Entity
    @Inheritance(strategy=InheritanceType.JOINED)
    public class Mobile implements Serializable {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        @Column(name="id_mobile")
        private Integer id;
    
        // Some fields
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-27
      相关资源
      最近更新 更多