【问题标题】:Hibernate IS-A relation mappingHibernate IS-A 关系映射
【发布时间】:2020-12-04 14:41:43
【问题描述】:

我有一个实体模型 (a) 和一些其他实体 (x),例如手机、平板电脑、汽车等。

entities(x) 具有引用 model(a) 的主键的主键,因此entities(x) 只能采用 model(a) 实体的值。 我说的是 IS-A 关系。

我还需要从两端访问。

我需要有关休眠映射的帮助。 我现在做什么但不起作用:

  • 模型实体
@Data
@Entity(name = "Model")
@Table(name = "model", schema = "mysch")
public class Model {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "model_id", columnDefinition = "BIGINT UNSIGNED")
    private long id;

    @Column(name = "description", length = 255, nullable = false, unique = true)
    private String description;

    @OneToOne(mappedBy = "model")
    private Mobile mobile;
  • 移动实体
@Data
@Entity(name = "Mobile")
@Table(name = "mobile", schema = "mysch")
public class Mobile {

    @Id
    @Column(name = "mobile_id", columnDefinition = "BIGINT UNSIGNED")
    private long id;

    @OneToOne
    @JoinColumn(name = "mobile_id", referencedColumnName = "model_id", nullable = false, foreignKey = @ForeignKey(name = "FK_Mobile_Model"))
    private Model model;

我想要的是在移动表中创建一个引用模型表的 PK 的 PK。

【问题讨论】:

  • 关系似乎不对。据我了解,每个Mobile 都有一个Model,但一个Model 可以被多个Mobiles 引用。那正确吗?如果是这样,您应该在Mobile 中使用@ManyToOne 关系,并可能在Model 上使用@OneToMany 关系。
  • 不,抱歉,如果我的解释不够好。手机是一个PK,所以它必须是独一无二的。因此,假设模型具有 ids: 1,2,3,4,5 。 id = 1 可用于移动设备。 id = 2 也可用于移动设备。 id =3 可用于汽车。但是 id =1 不能再次在移动设备中使用。两个id都是PK,所以是唯一的..

标签: java hibernate annotations mapping


【解决方案1】:

我可能已经找到了解决方案。 似乎现在可以工作。稍后我将进行 jpa 查询以对其进行测试。尽管数据库中的模式似乎正是我想要的。 这是我所做的:

  • 模型实体
@Data
@Entity(name = "Model")
@Table(name = "model", schema = "sch")
public class Model {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "model_id", columnDefinition = "BIGINT UNSIGNED")
    private long id;

    @Column(name = "description", length = 255, nullable = false, unique = true)
    private String description;

    @OneToOne(mappedBy = "model")
    private Mobile mobile;

}
  • 移动
@Data
@Entity(name = "Mobile")
@Table(name = "mobile", schema = "sch")
public class Mobile {

    @Id
    @Column(name = "mobile_id", columnDefinition = "BIGINT UNSIGNED")
    private long id;

    @OneToOne
    @MapsId
    private Model model;

}

虽然我不喜欢生成的移动端 PK 列名......它就像: “model_model_id”。

虽然它似乎运作良好......但我遇到了一个问题。我明白了:

Exception in thread "JavaFX Application Thread" java.lang.StackOverflowError
at java.base/java.lang.String.equals(String.java:1009)
at com.dc.sch.entity.Model.equals(Model.java:6)
at com.dc.sch.entity.Mobile .equals(Mobile .java:6)
at com.dc.sch.entity.Model.equals(Model.java:6)
at com.dc.sch.entity.Mobile .equals(Mobile .java:6)
at com.dc.sch.entity.Model.equals(Model.java:6)
at com.dc.sch.entity.Mobile .equals(Mobile .java:6)
at com.dc.sch.entity.Model.equals(Model.java:6)

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 1970-01-01
    • 1970-01-01
    • 2020-01-16
    • 2020-10-11
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多