摘自圣思园Hibernate 26.组件映射深度
解析
上一篇讲了如何通过配置Student实现Serializable
接口来实现复合
主键查询。
http://alleni123.iteye.com/admin/b
logs/1981608
这里要讲一下如何通过
组件来完成同样的功能。
先新建一个StudentPrimaryKey.java
class="java" name="code">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
<hibernate-mapping package="composite_primary">
<class name="Student" table="test_student">
<!-- composite-id表示复合主键 -->
<!-- name表示Student类中用于表示联合主键的元素的名字 -->
<composite-id name="pri" class="StudentPrimarykey">
<!-- key-property表示组成主键的元素 -->
<key-property name="cardId" column="card_id" type="string"/>
<key-property name="name" column="name" type="string"/>
</composite-id>
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
最后执行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