接上一篇博客:http://www.cnblogs.com/tengpan-cn/p/5551323.html
主键类不需要写任何注解,表对象类使用@IdClass注解
在表对象类前面加@IdClass(value=主键类名.class)然后,表对象类中也不必包含主键类,直接分成各个属性即可。在多个属性前加@ID
添加主键类,注意必须实现Serializable接口
package com.pt.hibernate; import java.io.Serializable; public class UnionId implements Serializable{
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
String schoolName;
int id;
}
UnionId.java
package com.pt.hibernate; import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass; @Entity
@IdClass(value=UnionId.class)
public class Student {
String schoolName;
int id;
String stuName; public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
@Id
public String getSchoolName() {
return schoolName;
}
public void setSchoolName(String schoolName) {
this.schoolName = schoolName;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} }
Student.java
生成表的语句:
create table Student (
id integer not null,
schoolName varchar(255) not null,
stuName varchar(255),
primary key (id, schoolName)
) ENGINE=InnoDB