一、 hibernate联合主键类的规则
1. 实现Serializable接口
2. 重写hashCode与equals方法
二、hibernate联合主键的实体类规则原因(与上面规则顺序对应)
1. Hibernate要根据数据库的联合主键来判断某两行记录是否是一样的,如果一样那么就认为是同一个对象,如果不一样,那么就认为是不同的对象。这反映到程序领域中就是根据hashCode与equals方法来判断某两个对象是否能够放到诸如Set这样的集合当中;
2. 使用get或load方法的时候需要先构建出来该实体的对象,并且将查询依据(联合主键)设置进去,get或load方法的第二个参数需要序列化。
public Object get(Class clazz,Serializable id)
三、 hibernate联合主键的使用
PrimaryKey.java
public class PrimaryKey implements Serializable{
// 属性
private String cardID;
private String name;
//get、set方法省略
...
// 重写EQUAL方法
public boolean equals(Object other) {
if ((this == other))
return true;
if ((other == null))
return false;
if (!(other instanceof PrimaryKey))
return false;
PrimaryKey castOther = (PrimaryKey) other;
return ((this.getCardID() == castOther.getCardID()) || (this.getCardID() != null && castOther.getCardID() != null && this.getCardID().equals(castOther.getCardID())))&& ((this.getName() == castOther.getName()) || (this.getName() != null && castOther.getName() != null && this.getName().equals(castOther.getName())));
}
// 重写HASHCODE方法
public int hashCode() {
int result = 17;
result = 37 * result + (getSpId() == null ? 0 : this.getSpId().hashCode());
result = 37 * result + (getName() == null ? 0 : this.getName().hashCode());
return result;
}
}
Student.java
public class Student {
// 属性
private PrimaryKey primaryKey; // 联合主键类
private int age;
//set、get方法省略
}
Student.hbm.xml
<class name="bean.Student" table="student">
<!--PrimaryKey为自定义的主键类-->
<composite-id name="primaryKey" class="bean.PrimaryKey">
<!--name及cardID为PrimaryKey类中的属性-->
<key-property name="name" column="student_name" type="string"></key-property>
<key-property name="cardID" column="card_id" type="string"></key-property>
</composite-id>
<property name="age" column="student_age" type="int"></property>
</class>
hibernate中使用
// 获取
public Student get(Serializable id) throws Exception {
Object obj = this.getHibernateTemplate().get(Student.class,id);
if (obj == null) {
return null;
} else {
return (Student) obj;
}
}