在Hibernate中,有3中方法可以设置联合主键
1:使用Embeddable
此方法是在主键类前加入@Embeddable
然后在主键类对象的get方法上加入@Id即可
示例:
//此类为Teacher的主键类
package com.freedom.pk;
import java.io.Serializable;
import javax.persistence.Embeddable;
@Embeddable
public class Teacher_PK 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;
}
}
package com.freedom.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import com.freedom.pk.Teacher_PK;
@Entity
public class Teacher {
private Teacher_PK teacher_PK;
@Id
public Teacher_PK getTeacher_PK() {
return teacher_PK;
}
public void setTeacher_PK(Teacher_PK teacher_PK) {
this.teacher_PK = teacher_PK;
}
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2:使用EmbeddedId
此方法比较简单,只需在主键类对象的get方法上加入@EmbeddedId即可
示例:
package com.freedom.pk;
import java.io.Serializable;
public class Teacher_PK 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;
}
}
package com.freedom.model;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import com.freedom.pk.Teacher_PK;
@Entity
public class Teacher {
private Teacher_PK teacher_PK;
private int age;
@EmbeddedId
public Teacher_PK getTeacher_PK() {
return teacher_PK;
}
public void setTeacher_PK(Teacher_PK teacher_PK) {
this.teacher_PK = teacher_PK;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
3:使用IdClass
在类前面加入@IdClass(value=xxxxx.class) xxxxx为主键类的类名,当只有一个参数时,我们可以直接省略写为@IdClass(xxxxx.class)
并且在主键元素的每个对象前加入@Id
示例:
package com.freedom.pk;
import java.io.Serializable;
public class Teacher_PK 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;
}
}
package com.freedom.model;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import com.freedom.pk.Teacher_PK;
@Entity
@IdClass(Teacher_PK.class)
public class Teacher {
private int id;
private String name;
private int 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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
我们比较常用的是第二种和第三中方法,第一种一般不用。