[英]Using same entity twice in another entity in hibernate
Let us say a class/entity named student which contains an id, father's occupation and mother's occupation and the entity classes are like this 让我们说一个名为student的类/实体,其中包含一个id,父亲的职业和母亲的职业,而实体类是这样的
Student class 学生班
@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;
}
and the Occupation class 和职业班
@Entity
@Table(name = "occupation")
public class Occupation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "occupationId")
int occupationId;
@Column
String title;
}
When I tried @OneToOne
mapping for both father's occupation and mother's occupation it is throwing exception, Repeated column in mapping for entity
. 当我尝试对父亲的职业和母亲的职业进行
@OneToOne
映射时,都抛出异常, Repeated column in mapping for entity
。 I tried adding @Column(name="<columnName>")
, but it is not allowed. 我尝试添加
@Column(name="<columnName>")
,但这是不允许的。 I really want those two fields, fathersOccupation
and mothersOccupation
with oneToOne
mapping in the student table. 我真的希望这两个领域,
fathersOccupation
和mothersOccupation
与oneToOne
在学生表映射。
@JoinColumn specify the name of the FK Column in your entity. @JoinColumn指定您实体中FK列的名称。
Your student entity have 2 FKs toward occupation, one for fathersOccupation and another one for mothersOccupation and you define mapping twice for the same. 您的学生实体有2个关于职业的FK,一个是针对父亲的职业,另一个是针对母亲的职业,您为同一职业定义了两次映射。 Ideally you should have fathers_occupation_id and mothers_occupation_id field in your student table and same attributes in your entity.
理想情况下,您的学生表中应具有fathers_occupation_id和mothers_occupation_id字段,并且实体中应具有相同的属性。
So you should put for each one the corresponding column name in your student table. 因此,您应该在学生表中为每一个输入相应的列名。
@JoinColumn(name ="fathers_occupation_id")
Occupation fathersOccupation;
@JoinColumn(name="mothers_occupation_id")
Occupation mothersOccupation;
If someone interesting in, the solution that worked for me was to rename mapping field in entity with @ManyToOne annotation and add prefix before "account_id": 如果有人感兴趣,对我有用的解决方案是使用@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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.