首页 > 代码库 > Hibernate学习之路(三)

Hibernate学习之路(三)

简要聊一聊 组合主键映射

一:组合主键映射(数据库中某张表有多个主键)

  比如有一个学生成绩类,有属性:stuId,subjectId,result. 其中stuId 和 subjectId 对应映射表中的组合主键(stuId,subjectId)

  1、编写组合主键的类,该类必须实现Serializable接口

 1 package cn.pojo;
 2 
 3 import java.io.Serializable;
 4 
 5 public class ScoreId implements Serializable{
 6     private int stuId;
 7     private int subjectId;
 8     
 9     public int getStuId() {
10         return stuId;
11     }
12     public void setStuId(int stuId) {
13         this.stuId = stuId;
14     }
15     public int getSubjectId() {
16         return subjectId;
17     }
18     public void setSubjectId(int subjectId) {
19         this.subjectId = subjectId;
20     }
21     
22 }

  2、在主类中引用该类

 1 package cn.pojo;
 2 
 3 public class Score {
 4     private ScoreId scoreId;
 5     private int resule;
 6     
 7     public ScoreId getScoreId() {
 8         return scoreId;
 9     }
10     public void setScoreId(ScoreId scoreId) {
11         this.scoreId = scoreId;
12     }
13     public int getResule() {
14         return resule;
15     }
16     public void setResule(int resule) {
17         this.resule = resule;
18     }
19     
20 }

  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.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"></property>
    </class>
</hibernate-mapping>

  4、测试

package cn.test;

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

import cn.pojo.Score;
import cn.pojo.ScoreId;

public class TestHibernate {
    public static void main(String[] args) {
        //通过Configuration对象创建SessionFactory对象
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        //创建Session对象
        Session s = sf.openSession();
        //开启事务
        s.beginTransaction();
        
        //我们只需要关注这里的事务。
        Score score = new Score();
        ScoreId si = new ScoreId();
        si.setStuId(1);
        si.setSubjectId(3);
        score.setScoreId(si);
        score.setResult(89);
        s.save(score);
        
        //提交事务
        s.getTransaction().commit();
        //关闭Session
        s.close();
        //关闭SessionFactory
        sf.close();
    }
}

 

  

Hibernate学习之路(三)