【问题标题】:Using same entity twice in another entity in hibernate在休眠中的另一个实体中使用相同的实体两次
【发布时间】:2017-11-18 10:21:54
【问题描述】:

假设一个名为student的类/实体包含一个id,父亲的职业和母亲的职业,实体类是这样的

学生班

@Entity
@Table(name = "student")
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(nullable = false, unique = true, updatable = false)
    private int id;

    @OneToOne
    @JoinColumn(name = "occupationId")
    Occupation fathersOccupation;

    @OneToOne
    @JoinColumn(name = "occupationId")
    Occupation mothersOccupation;

}

职业类别

@Entity
@Table(name = "occupation")
public class Occupation {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "occupationId")
    int occupationId;

    @Column
    String title;

}

当我尝试为父亲的职业和母亲的职业进行@OneToOne 映射时,它抛出异常Repeated column in mapping for entity。我尝试添加@Column(name="<columnName>"),但不允许。我真的很想要这两个字段,fathersOccupationmothersOccupation 在学生表中带有 oneToOne 映射。

【问题讨论】:

    标签: java hibernate hibernate-mapping one-to-one


    【解决方案1】:

    @JoinColumn 指定实体中 FK 列的名称。

    您的学生实体有 2 个针对职业的 FK,一个针对 FathersOccupation,另一个针对 MothersOccupation,您为相同定义了两次映射。理想情况下,您的学生表中应该有 fathers_occupation_idmothers_occupation_id 字段,并且您的实体中应该有相同的属性。

    所以你应该在你的学生表中为每一个输入对应的列名。

    @JoinColumn(name ="fathers_occupation_id")
    Occupation fathersOccupation;
    
    @JoinColumn(name="mothers_occupation_id")
    Occupation mothersOccupation;
    

    【讨论】:

      【解决方案2】:

      如果有人对此感兴趣,对我有用的解决方案是使用 @ManyToOne 注释重命名实体中的映射字段并在“account_id”之前添加前缀:

      @ManyToOne
      @JoinColumn(name = "from_account_id") // add from_
      private Account fromAcc;
      @ManyToOne
      @JoinColumn(name = "to_account_id") // add to_
      private Account toAcc;
      

      【讨论】:

      • 以及在帐户实体中为多对一注释提及的内容。
      猜你喜欢
      • 1970-01-01
      • 2015-12-02
      • 1970-01-01
      • 2021-07-19
      • 1970-01-01
      • 1970-01-01
      • 2014-01-03
      • 1970-01-01
      • 2011-07-18
      相关资源
      最近更新 更多