【6.0】组合主键映射

通过组件来实现组合主键的步骤:

1.编写组合主键的类,该类必须实现Serializable接口,生成对应的get/set方法;最好实现equals和hashCode方法.

public class ScoreId implements Serializable{
	private int stuId;//学生编号
	private int subjectId;//科目编号
	public int getStuId() {
		return stuId;
	}
	public void setStuId(int stuId) {
		this.stuId = stuId;
	}
	public int getSubjectId() {
		return subjectId;
	}
	public void setSubjectId(int subjectId) {
		this.subjectId = subjectId;
	}
}

 

2.在主类中引用对应组件

/**
 * 成绩
 * */
public class Score {
	private ScoreId scoreId;
	private double result;//成绩
	
	public ScoreId getScoreId() {
		return scoreId;
	}
	public void setScoreId(ScoreId scoreId) {
		this.scoreId = scoreId;
	}
	public double getResult() {
		return result;
	}
	public void setResult(double result) {
		this.result = result;
	}
}

 

3.映射文件的编写

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.siggy.pojo">
	<class name="Score">
		<!-- 组合主键 -->
		<composite-id name="scoreId" class="ScoreId">
			<key-property name="stuId"></key-property>
			<key-property name="subjectId"></key-property>
		</composite-id>
		<property name="result"/>
	</class>
</hibernate-mapping>

  

4.测试代码【运行该方法:public void testSave() throws HibernateException{}】

package cn.siggy.test;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

import cn.siggy.pojo.Score;
import cn.siggy.pojo.ScoreId;
import cn.siggy.util.HibernateUtil;

public class HibernateTest {
	@Test
	public void testCreateDB(){
		Configuration cfg = new Configuration().configure();
		SchemaExport se = new SchemaExport(cfg);
		//第一个参数 是否生成ddl脚本  第二个参数  是否执行到数据库中
		se.create(true, true);
	}
	@Test
	public void testSave() throws HibernateException{
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtil.getSession();
			tx = session.beginTransaction();
			
			Score s = new Score();
			ScoreId sid = new ScoreId();
			sid.setStuId(2);
			sid.setSubjectId(6);
			s.setResult(89);
			s.setScoreId(sid);
			
			session.save(s);
			
			tx.commit();
			
		}catch (HibernateException e) {
			if(tx!=null)
				tx.rollback();
			e.printStackTrace();
			throw e;
		}finally{
			HibernateUtil.closeSession();
		}
	}
}

  

5.测试结果

控制台信息:


 

 

数据库表变化:

 

 

posted @ 2017-04-06 22:46  chxbar  阅读(148)  评论(0编辑  收藏  举报