在hibernate中使用联合主键可以对某个对象对应的联合主键建立一个主键类,这个类中包含了主键的属性,并且这个类必须实现Serializable接口,
重写equals,hashcode方法。
如对Student进行持久化,假设它的联合主键是sid,sname,那么可以它建立一个对应的主键类,类中包含了sid,sname
如下:
package vo;
import java.io.Serializable;
public class StudentPK implements Serializable{
private int sid;
private String sname;
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + sid;
result = prime * result + ((sname == null) ? 0 : sname.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
StudentPK other = (StudentPK) obj;
if (sid != other.sid)
return false;
if (sname == null) {
if (other.sname != null)
return false;
} else if (!sname.equals(other.sname))
return false;
return true;
}
}
而Student类如下:
package vo;
public class Student {
private StudentPK pk;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public StudentPK getPk() {
return pk;
}
public void setPk(StudentPK pk) {
this.pk = pk;
}
}
然后配置Student.hbm.xml
<hibernate-mapping>
<class name="vo.Student" table="student">
<composite-id name="pk" class="vo.StudentPK">
<key-property name="sid"/>
<key-property name="sname"/>
</composite-id>
<property name="age"/>
</class>
</hibernate-mapping>
写测试类
package vo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
public class StudentTest {
private static SessionFactory sf=null;
@BeforeClass
public static void getSessionFactory(){
Configuration config = new AnnotationConfiguration();
sf = config.configure().buildSessionFactory();
}
@AfterClass
public static void closeSessionFactory(){
sf.close();
}
@Test
public void save(){
StudentPK pk = new StudentPK();
pk.setSid(1);
pk.setSname("david");
Student s = new Student();
s.setPk(pk);
s.setAge(22);
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close();
}
}