上一篇讲了如何通过配置Student实现Serializable接口来实现复合主键查询。
http://alleni123.iteye.com/admin/blogs/1981608
这里要讲一下如何通过 组件来完成同样的功能。
先新建一个StudentPrimaryKey.java
package composite_primary; import java.io.Serializable; public class StudentPrimarykey implements Serializable { private String cardId; private String name; @Override public int hashCode() { ... } @Override public boolean equals(Object obj) { ... } }
也就是把之前的Student类的cardId和name放到了这里,并在这个类中重载了这两个元素的hashCode和equals方法。
然后再把Student.java改一下:
public class Student { private StudentPrimarykey pri; private int age; }
最后是Student.hbm.xml
最后执行configure(),生成SQL语句:
create table test_student (card_id varchar2(255 char) not null, name varchar2(255 char) not null, age number(10,0), primary key (card_id, name));
和上一篇的SQL语句时完全一样的。
插入
Session session=HibernateUtil.openSession(); Transaction tx=session.beginTransaction(); StudentPrimarykey key1=new StudentPrimarykey("111", "alleni"); Student s1=new Student(); s1.setPri(key1); s1.setAge(22); StudentPrimarykey key2=new StudentPrimarykey("222", "eline"); Student s2=new Student(); s2.setPri(key2); s2.setAge(33); session.save(s1); session.save(s2); tx.commit();
查询
Session session=HibernateUtil.openSession(); StudentPrimarykey key1=new StudentPrimarykey("111", "alleni"); Student s=(Student) session.get(Student.class,key1); System.out.println(s.getAge()); //22