1.17 表之间的关系(联合主键的一对一关系)

husband类和wife类为一对一关联关系,其中wife为联合主键。

1.wife类。id和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;
}

}

2.wifepk类

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;
}

}

3.husband类,要实现husband类的wife字段与wife类的联合主键关联。主要设置在这里

@Entity
public class Husband {
private int id;
private String name;
private Wife wife;
@Id
@GeneratedValue
public int getId() {
return id;
}

public String getName() {
return name;
}
@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;
}

}


你可能感兴趣的:(hibernate文章)