xml方式处理联合主键:
以有两个主键:id和name的student表为例。
先创建个主键类:
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(); } }
写model:
package com.bjsxt.hibernate;
public class Student {
private StudentPK pk; private int age; private String sex; private boolean good; public boolean isGood() { return good; } public void setGood(boolean good) { this.good = good; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public StudentPK getPk() { return pk; } public void setPk(StudentPK pk) { this.pk = pk; } }
映射关系:Student.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "><hibernate-mapping>
<class name="com.bjsxt.hibernate.Student"> <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" /> <property name="sex" /> <property name="good" type="yes_no"></property> </class> </hibernate-mapping>
Annotation(注解)处理联合主键
三种方法:
将主键类注解为@Embeddable并将model中的属性——主键类的对象注解为@Id
将主键类的对象充当的组件的属性注解为@EmbeddedId,仍然需要主键类。
将类注解为@IdClass(主键类.class ),并将该实体中所有属于主键的属性都注解为@Id