public class Husband {
private int id;
private String name;
private Wife wife;
@Id
@GeneratedValue
public int getId() {
return id;
}
public String getName() {
return name;
}
@JoinColumns
Wife类中建立联合主键,建立方式参考 ID生成策略中的联合主键部分
Husband类中写Wife对象属性,并在其get方法上写@OneToOne即可完成一对一外键映射
若想要指定生成的外键名则需使用@JoinColumns注解,如下:
@OneToOne
@JoinColumns( { @JoinColumn(name ="wifeid", referencedColumnName = "id"),
@JoinColumn(name ="wifename", referencedColumnName = "name") })
/*@JoinColumns用于在一对一外键关联存在联合主键情况时指定生成的外键字段名称
@JoinColumns的参数为@JoinColumn数组 @JoinColumn内除需指定name属性外还需指定
referencedColumnName属性值作用是可指定生成的字段名所对应的目标表字段名*/
@OneToOne
@JoinColumns(
{
@JoinColumn(name="wifeId", referencedColumnName="id"),
@JoinColumn(name="wifeName", referencedColumnName="name")
}
)
public Wife getWife() {
return wife;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setWife(Wife wife) {
this.wife = wife;
}
}
public class WifePK implements Serializable {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
@IdClass(WifePK.class)
public class Wife {
private int id;
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Wife w=new Wife();
w.setName("w");
Husband h=new Husband();
h.setName("h");
h.setWife(w);
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(w);
session.save(h);
session.getTransaction().commit();