Hibernate基于XML的----联合主键配置

基于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();
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值