---
title: "Hibernateday05对象当中的几个属性组合作为表的主键【实体类属性的复合主键】"
author: "lonemoon"
date: "2012-07-20T23:47:10Z"
tags: []
categories: ["编程语言"]
slug: "hibernateday05"
draft: false
lastmod: "2012-07-20T23:47:10Z"
id: 1602507
url: "https://lonemoon.iteye.com/blog/1602507"
---

复合主键  
   注意：1.对象必须实现序列化接口  
  1.对象当中的几个属性组合作为表的主键【实体类属性的复合主键】  
   O    StudnetMsg  
         stuId//学号  
     courseId//课程  
     grade//分数  
  R create table g\_stuMsg(  
     stuId integer,  
     courseId integer,  
     grade number(3,1),//数字总共3个，小数点后面一位  
     primary key (stuId,courseId)  
  );  
   
  M 映射文件  
    1.复合主键而言，主键的控制不能使用&lt;id&gt;标签  
      &lt;composite-id&gt;  
        &lt;key-property name="属性名" column="对应的列名" type="类型" /&gt;  
    ...  
      &lt;/composite-id&gt;

 

1.O在com.jsu.hb.pojo包中创建实体类

```
package com.jsu.hb.pojo;

import java.io.Serializable;

public class StudentInfo implements Serializable{
	private Integer studentId;
	private Integer courseId;
	private Double grade;
	public Integer getStudentId() {
		return studentId;
	}
	public void setStudentId(Integer studentId) {
		this.studentId = studentId;
	}
	public Integer getCourseId() {
		return courseId;
	}
	public void setCourseId(Integer courseId) {
		this.courseId = courseId;
	}
	public Double getGrade() {
		return grade;
	}
	public void setGrade(Double grade) {
		this.grade = grade;
	}
	
}
```

 2.建表

```
create table g_stuInfo(
       studentId integer,
       courseId integer,
       grade number(4,1),
       primary key(studentId,courseId)
)
select * from g_stuInfo
```

 3.M提供映射文件在stupk.hbm.xml文件中

```
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
	<!-- name:所操作对象的全路径 table:该对象所对应的表名 -->
	<class name="com.jsu.hb.pojo.StudentInfo" table="g_stuInfo">
		<composite-id>
			<key-property name="studentId" column="studentId"></key-property>
			<key-property name="courseId" column="courseId"></key-property>
		</composite-id>
		<!-- 普通属性的配置，非主键属性的配置 -->
		<property name="grade" column="grade"></property>
	</class>
</hibernate-mapping>
```

 4.在hibernate.cfg.xml中对映射文件进行注册

```
<!DOCTYPE hibernate-configuration PUBLIC
	"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
	"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
	<session-factory> 
		<!-- show_sql:是否显示hibernate执行的SQL语句，默认为false -->
		<property name="show_sql">true</property>
		<!-- show_sql:是否显示hibernate执行格式化输出的SQL语句，默认为false -->
		<property name="format_sql">true</property>
		<!-- 配置与数据库连接的参数 -->
		<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
		<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:oracle</property>
		<property name="connection.username">scott</property>
		<property name="connection.password">tiger</property>
		<!-- 2.自身属性相关的配置
			dialect:方言
			hibernate根据dialect的配置进行特定数据性能方面的调优
		 -->
		<property name="dialect">org.hibernate.dialect.Oracle9iDialect</property>
		<mapping resource="com/jsu/hb/pojo/stupk.hbm.xml"></mapping>
	</session-factory>
</hibernate-configuration>
```

 5.提供工具类HibernateUtil.java

```
package com.jsu.hb.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sf;
	private static ThreadLocal<Session> tl= new ThreadLocal<Session>();
	static{
		try{
				Configuration cfg = new Configuration();
				cfg.configure();
				sf=cfg.buildSessionFactory();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static Session openSession(){
		return sf.openSession();
	}
	public static Session getCurrentSession(){
		Session session = tl.get();//先从储存的线程中查找
		if(session==null){
			session=openSession();
			tl.set(session);
			return session;
		}
		return session;
	}
}
```

 6.提供测试类TestStuPK.java

```
package com.jsu.hb.test;

import java.io.Serializable;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.jsu.hb.pojo.StudentInfo;
import com.jsu.hb.util.HibernateUtil;

public class TestStuPK {
	@Test
	public void save(){
		StudentInfo s = new StudentInfo();
		s.setStudentId(2);
		s.setCourseId(2);
		s.setGrade(80.5);
		
		Session session = HibernateUtil.getCurrentSession();
		Transaction tx = session.getTransaction();
		tx.begin();
		session.save(s);
		tx.commit();
	}
}
```