这就是我的SQL表格:
CREATE TABLE IF NOT EXISTS `test`.`Families` (
`id` INT NOT NULL AUTO_INCREMENT,
`mother_id` INT DEFAULT NULL ,
`father_id` INT DEFAULT NULL ,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS `test`.`Parents` (
`id` INT NOT NULL AUTO_INCREMENT,
`first_name` VARCHAR(50) DEFAULT NULL,
`last_name` VARCHAR(50) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
这就是我家庭实体的样子:
@Entity
@Table(name="Families")
public class Family implements Serializable {
@Id
@Column(name="id")
private String id;
@Column(name="mother_id")
private int mother;
@Column(name="father_id")
private int father;
}
哪一个很好,但我真的很喜欢,如果我可以做这样的事情(注意我也有一个已经定义的父实体):
@Entity
@Table(name="Families")
public class Family implements Serializable {
@Id
@Column(name="id")
private String id;
@OneToOne
@Column(name="mother_id")
private Parent mother;
@OneToOne
@Column(name="father_id")
private Parent father;
}
我怎么能做到这一点?
答案 0 :(得分:1)
实际上,Hibernate会为你做一切。
@Column
已经有@OneToOne
或其他关联注释的列添加注释field
+ _id
组成),则应使用@JoinColumn
注释@Entity
@Table(name="Families")
public class Family implements Serializable {
@Id
@Column(name="id")
private String id;
@OneToOne
@JoinColumn(name = "mother_idd")
private Parent mother;
@OneToOne
@JoinColumn(name = "father_idd")
private Parent father;
}