基于XML配置实现联合主键
部门hibernate配置代码省略了
配置文件内容:
利用标签composite-id
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="com.chaosju.po.Student" table="student" schema="user">
<span style="color:#ff0000;"><composite-id class="com.chaosju.po.StudentPK" name="pk">
<key-property name="id"/>
<key-property name="name"/>
</composite-id>
</span>
<property name="age" > </property>
<property name="sex" > </property>
</class>
</hibernate-mapping>
测试类:主键类
package com.chaosju.po;
import java.io.Serializable;
/*
主键类要注意一下两点
1.继承Serializable接口
2.重写equls方法和hashcode方法
*/
public class StudentPK implements 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 obj) {
if(obj instanceof StudentPK){
StudentPK pk = (StudentPK)obj;
if(this.id ==pk.getId()&&this.name.equals(pk.getName()) ){
return true;
}
}
return false;
}
@Override
public int hashCode() {
return this.name.hashCode();
}
}
测试类:po类
package com.chaosju.po;
public class Student {
private StudentPK pk;
private int age;
private String sex;
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;
}
}
主要测试类
import org.hibernate.Session;
import com.chaosju.po.Student;
import com.chaosju.po.StudentPK;
import com.chaosju.util.HibernateUtil;
public class Test {
public static void main(String[] args) {
Student student = new Student();
StudentPK pk = new StudentPK();
pk.setId(33);
pk.setName("juchao");
student.setPk(pk);
student.setAge(13);
student.setSex("sex");
//创建session
Session session = HibernateUtil.getSession();
//开启事务
session.beginTransaction();
//保存数据
session.save(student);
//事务提交
session.getTransaction().commit();
session.close();
}