ID生成策略之联合主键xml实现
Student.hbm.xml的配置: <hibernate-mapping package="org.hibernate.first.model"> <class name="Student"> <composite-id name="pk" class="org.hibernate.first.model.StudentPK"> <key-property name="id"></key-property> <!--主键属性--> <key-property name="name"></key-property> <!--主键属性--> </composite-id>
<property name="age" column="age"/> <!--剩余的其他属性--> </class> </hibernate-mapping> 主键类的编写: public class StudentPK 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; } @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(); } } model类的编写: public class Student { private int age; private StudentPK pk;
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; }
} 测试类的编写: public class TestStudent { static Configuration cfg = null; static SessionFactory sessionFactory = null;
@Before public void before(){ System.out.println("this is before"); }
@BeforeClass public static void beforeClass(){ cfg = new AnnotationConfiguration(); sessionFactory = cfg.configure().buildSessionFactory(); } @Test public void testStudent(){ Student s = new Student(); StudentPK pk = new StudentPK(); pk.setId(1); pk.setName("jim"); s.setPk(pk); //s.setName("jim"); s.setAge(20);
Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(s); session.getTransaction().commit(); session.close(); }
@After public void after(){ System.out.println("this is After."); }
@AfterClass static public void afterClass(){ sessionFactory.close(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |