hibernate----联合主键映射

以课程表和学生表为例,课程表有课程编码和课程名称,学生表有学号和姓名,当学号和课程编码都确定时,就可以确定该学生这门课程的分数。
1.创建学生类和课程表类,以及把学生的学号,课程的编号组成一个实体类,共三个实体类

(1)学生类 student.class
package entity;

public class Student {
private int num;
private String name;

public int getNum() {
    return num;
}
public void setNum(int num) {
    this.num = num;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
(2)课程表类(感觉这个类没有用到,其实可以不写) Test.class

package entity;

public class Test {

private int Tnum;
private String classname;
public int getTnum() {
    return Tnum;
}
public void setTnum(int tnum) {
    Tnum = tnum;
}
public String getClassname() {
    return classname;
}
public void setClassname(String classname) {
    this.classname = classname;
}

}
(3) 主键类 Pass.class
package entity;

import java.io.Serializable;

public class Mainkey implements Serializable{

private static final long serialVersionUID = 1L;
private int num;
private int Tnum;
public int getNum() {
    return num;
}
public void setNum(int num) {
    this.num = num;
}
public int getTnum() {
    return Tnum;
}
public void setTnum(int tnum) {
    Tnum = tnum;
}

}
}
2.配置实体类的映射文件
(1)pass.hbm.xml

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">


   
   
    
   
    
   

3.配置hibernate.cfg.xml
其他的配置相同,主要是把pass类的配置文件加进去
这一句 “

4.写测试类
package text;

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

import entity.Mainkey;

import entity.Pass;

public class Text02 {

public static void main(String[] args) {
    Configuration cfg=new Configuration().configure("hibernate.cfg.xml");
    SessionFactory sessionFactory=cfg.buildSessionFactory();
    Session session=sessionFactory.openSession();
    Transaction ts=session.beginTransaction();
    
    Mainkey mainkey=new Mainkey();
    mainkey.setNum(4017);
    mainkey.setTnum(10001);
    
    Pass pass=new Pass();
    pass.setGrade(90);
    pass.setMainkey(mainkey);
    session.save(pass);
    ts.commit();
    session.close();
    
    
    
    
    
}

}

你可能感兴趣的:(hibernate----联合主键映射)