标签:
xml:composite-id
要重写equals,hashCode方法, 还要序列化
1. 新建一个主键类: StudentPK.java, 注意需要序列化.还要重写equals和hashCode:
package com.bjsxt.hibernate; public class StudentPK implements java.io.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; } @Override public boolean equals(Object o){ if(o instanceof StudentPK){ StudentPK pk=(StudentPK)o; if(this.id==pk.getId()&&this.name.equals(pk.getName())){ return true; } } return false; } @Override public int hashCode(){ return this.name.hashCode(); } }
2. 删掉Student.java里的id和name的set和get方法, 新建一个主键对象及setter和getter:
package com.bjsxt.hibernate; public class Student { private StudentPK pk; private int age; public StudentPK getPk() { return pk; } public void setPk(StudentPK pk) { this.pk = pk; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
3. junit的测试方法改成:
@Test public void testStudentSave() { StudentPK pk=new StudentPK(); pk.setId(1); pk.setName("zhangsan"); Student s =new Student(); s.setPk(pk); s.setAge(23); Session session = sf.openSession(); session.beginTransaction(); session.save(s); session.getTransaction().commit(); session.close(); }
4. Student.hbm.xml改成:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.bjsxt.hibernate"> <class name="Student" table="_student"> <!-- <id name="id"> <generator class="native"></generator> </id> <property name="name"/> --> <composite-id name="pk" class="com.bjsxt.hibernate.StudentPK"> <key-property name="id"></key-property> <key-property name="name"></key-property> </composite-id> <property name="age"/> </class> </hibernate-mapping>
标签:
原文地址:http://www.cnblogs.com/wujixing/p/5413607.html