hibernate基础16:组合主键2
2021-02-17 16:18
标签:数据 类的属性 double imp 参数 oid sys close mini 1、Java实体bean类 2、配置hbm.xml 3、测试 hibernate基础16:组合主键2 标签:数据 类的属性 double imp 参数 oid sys close mini 原文地址:https://www.cnblogs.com/chai-blogs/p/12952439.htmlpackage com.project.pojo;
import java.io.Serializable;
public class ResultPk implements Serializable{
private int stuid;//学生id
private int subid;//学科id
public int getStuid() {
return stuid;
}
public void setStuid(int stuid) {
this.stuid = stuid;
}
public int getSubid() {
return subid;
}
public void setSubid(int subid) {
this.subid = subid;
}
}
package com.project.pojo;
import java.io.Serializable;
/**
* 如果组合索引是类的属性时,该类必须实现Serializable
* @author Administrator
*
*/
public class Result implements Serializable{
private ResultPk id;
private double score;
public ResultPk getId() {
return id;
}
public void setId(ResultPk id) {
this.id = id;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
xml version="1.0" encoding="UTF-8"?>
DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
hibernate-mapping package="com.project.pojo">
class name="Result" table="t_result">
composite-id name="id" class="ResultPk">
key-property name="stuid"/>
key-property name="subid"/>
composite-id>
property name="score" />
class>
hibernate-mapping>
package com.project.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.project.pojo.Result;
import com.project.pojo.ResultPk;
import com.project.util.HibernateUtil;
public class HibernateTest {
Session session = null;
Transaction ts = null;
@Before
public void setUp(){
session = HibernateUtil.getSession();
ts = session.beginTransaction();
}
@After
public void tearDown(){
HibernateUtil.closeSession();
}
@Test
public void testCreateDB(){
Configuration cfg = new Configuration().configure();
//使得hibernate映射信息转换为数据库识别的dll语言
SchemaExport se = new SchemaExport(cfg);
//第一个参数:是否打印dll语句
//第二个参数:是否将dll到数据库中执行
se.create(true, true);
}
@Test
public void testInit(){
try {
ResultPk pk = new ResultPk();
pk.setStuid(1);
pk.setSubid(1);
Result r = new Result();
r.setId(pk);
r.setScore(70.5);
session.save(r);
ts.commit();
} catch (Exception e) {
if(ts!=null)ts.rollback();
e.printStackTrace();
}
}
@Test
public void testSelect(){
ResultPk pk = new ResultPk();
pk.setStuid(1);
pk.setSubid(1);
Result r = (Result) session.get(Result.class, pk);
System.out.println(r.getScore());
}
}
文章标题:hibernate基础16:组合主键2
文章链接:http://soscw.com/index.php/essay/56643.html