xml的方法:
构造一个新的类存放主键,在类里面写主键,一定要重写equals和hashcode方法例如:
public class StudentPK implements java.io.Serializable{//需要实现可序列化的接口,数据转移的时候需要序列化
private int id;//get,set方法
private String name;//get和set方法
@Override
//equeals的方法用来保证唯一性,student的对象放到内存后,每个对象都有自己的studentPk,数据库是根据主键不同来区分的,内存里也是这样的,所以要重写equals方法
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
//对象放在了哈希表里,查找哈希表的时候首先查找hashcode,所以要用到hashCode方法
public int hashCode() {
return this.name.hashCode();
}
}
这个类写除了主键的字段对应的属性
public class Student {
private StudentPK pk;
private int age;
private String sex;
private boolean good;
//省略get和set方法
}
在Student.hbm.xml里写配置就行例如
<hibernate-mapping>
<class name="com.hibernate.Student">
<composite-id name="pk" class="com.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的方法:
1:将主键类注解为@Embeddable,并将主键在其他属性类中的主键对象设置为@Id例:
@Embeddable
public class TeacherPK{
....
}
publci class Teacher{
private TeacherPK pk;
@Id
public TeacherPK getPK(){}
}
2:将主键的属性注解为@Embeddable
public class TeacherPK{
private int id;
private String name;
....
}
publci class Teacher{
private TeacherPK pk;
@Embeddable
public TeacherPK getPK(){}
}
3:将类注解为@IdClass,并将该实体中所有属于主键的属性都注解为@Id
public class TeacherPK{
//什么都不用写,但是要保留,因为从数据库取出独享的时候要用到
}
@IdClass(value=TeacherPK.class)
publci class Teacher{
private int id;
private String name;
....
@Id
public int getId() {
return id;
}
@Id
public String getName() {
return name;
}
}