java中两个字段组合创建主键_java之hibernate之组合主键映射

1.在应用中经常会有主键是由2个或多个字段组合而成的。比如成绩表:

d1b6955f32cb56f4a085e766bd821ff0.png

第一种方式:把主键写为单独的类

2.类的设计:studentId,subjectId ,这两个主键是一个组件。所以可以采用组件映射的方式来完成。

主键写为单独类 ResultPk;

ResultPk.java

/***

*组合组件类必须实现序列化接口,只有实现了序列化才能使用

*session的get方法获取对象*/

public class ResultPk implementsSerializable{private intstudentId;private intsubjectId;publicResultPk() {

}public ResultPk(int studentId, intsubjectId) {super();this.studentId =studentId;this.subjectId =subjectId;

}public intgetStudentId() {returnstudentId;

}public void setStudentId(intstudentId) {this.studentId =studentId;

}public intgetSubjectId() {returnsubjectId;

}public void setSubjectId(intsubjectId) {this.subjectId =subjectId;

}

}

Result.java

public classResult {privateResultPk pk;private intscore;privateDate examDate;publicResult() {

}public Result(ResultPk pk, intscore, Date examDate) {super();this.pk =pk;this.score =score;this.examDate =examDate;

}publicResultPk getPk() {returnpk;

}public voidsetPk(ResultPk pk) {this.pk =pk;

}public intgetScore() {returnscore;

}public void setScore(intscore) {this.score =score;

}publicDate getExamDate() {returnexamDate;

}public voidsetExamDate(Date examDate) {this.examDate =examDate;

}

}

3.映射文件

4.测试

public classHibernateTest {/*** 生成数据库表的工具方法

**/@Testpublic voidtestCreateDB(){

Configuration cfg= newConfiguration().configure();

SchemaExport se= newSchemaExport(cfg);//第一个参数 是否打印sql脚本//第二个参数 是否将脚本导出到数据库中执行

se.create(true, true);

}/*** 初始化表数据*/@Testpublic voidtestInit(){

Session session= null;

Transaction tx= null;try{

session=HibernateUtil.getSession();

tx=session.beginTransaction();

ResultPk pk1= new ResultPk(1, 1);

ResultPk pk2= new ResultPk(1, 2);

Result r1= new Result(pk1, 90, new SimpleDateFormat("yyyy-MM-dd").parse("2016-09-12"));

Result r2= new Result(pk2, 83, new SimpleDateFormat("yyyy-MM-dd").parse("2016-09-22"));

session.save(r1);

session.save(r2);

tx.commit();

}catch(Exception e) {if(tx!=null)

tx.rollback();

}finally{

HibernateUtil.close();

}

}/**

*/@Testpublic voidtestGetData(){

Session session=HibernateUtil.getSession();

ResultPk pk1= new ResultPk(1, 1);

Result result= (Result)session.get(Result.class, pk1);

System.out.println(result.getScore()+"---"+result.getExamDate());

HibernateUtil.close();

}

}

第二种方式:直接通过一个类来描述

5.组合主键的第二种实现方式,直接通过一个类来描述

类结构

/*** 在类中有组合主键那么必须实现Serializable接口

**/

public class Result implementsSerializable{private intstudentId;private intsubjectId;private intscore;privateDate examDate;publicResult() {

}public Result(int studentId, intsubjectId) {super();this.studentId =studentId;this.subjectId =subjectId;

}public Result(int studentId, int subjectId, intscore, Date examDate) {super();this.studentId =studentId;this.subjectId =subjectId;this.score =score;this.examDate =examDate;

}public intgetStudentId() {returnstudentId;

}public void setStudentId(intstudentId) {this.studentId =studentId;

}public intgetSubjectId() {returnsubjectId;

}public void setSubjectId(intsubjectId) {this.subjectId =subjectId;

}public intgetScore() {returnscore;

}public void setScore(intscore) {this.score =score;

}publicDate getExamDate() {returnexamDate;

}public voidsetExamDate(Date examDate) {this.examDate =examDate;

}

}

6.映射文件

7.测试

public classHibernateTest {/*** 生成数据库表的工具方法

**/@Testpublic voidtestCreateDB(){

Configuration cfg= newConfiguration().configure();

SchemaExport se= newSchemaExport(cfg);//第一个参数 是否打印sql脚本//第二个参数 是否将脚本导出到数据库中执行

se.create(true, true);

}/*** 初始化表数据*/@Testpublic voidtestInit(){

Session session= null;

Transaction tx= null;try{

session=HibernateUtil.getSession();

tx=session.beginTransaction();

Result r1= new Result(1,1, 90, new SimpleDateFormat("yyyy-MM-dd").parse("2016-09-12"));

Result r2= new Result(1,2, 83, new SimpleDateFormat("yyyy-MM-dd").parse("2016-09-22"));

session.save(r1);

session.save(r2);

tx.commit();

}catch(Exception e) {if(tx!=null)

tx.rollback();

}finally{

HibernateUtil.close();

}

}/**

*/@Testpublic voidtestGetData(){

Session session=HibernateUtil.getSession();

Result result= new Result(1, 1);

result= (Result)session.get(Result.class, result);

System.out.println(result.getScore()+"---"+result.getExamDate());

HibernateUtil.close();

}

}

第三种方式:表结构不改变,但是组合主键代表的是外键

8.表结构不改变,但是组合主键代表的是外键

Student.java

public class Student implementsSerializable{private intid;privateString name;private intage;public Student(String name, intage) {super();this.name =name;this.age =age;

}publicStudent() {

}public intgetId() {returnid;

}public void setId(intid) {this.id =id;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}public intgetAge() {returnage;

}public void setAge(intage) {this.age =age;

}

}

Subject.java

public class Subject implementsSerializable{private intid;privateString name;publicSubject() {

}publicSubject(String name) {super();this.name =name;

}public intgetId() {returnid;

}public void setId(intid) {this.id =id;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}

}

Result.java

/*** 在类中有组合主键那么必须实现Serializable接口

**/

public class Result implementsSerializable{privateStudent student;privateSubject subject;private intscore;privateDate examDate;publicResult() {

}publicResult(Student student, Subject subject) {super();this.student =student;this.subject =subject;

}public Result(Student student, Subject subject, intscore, Date examDate) {super();this.student =student;this.subject =subject;this.score =score;this.examDate =examDate;

}publicStudent getStudent() {returnstudent;

}public voidsetStudent(Student student) {this.student =student;

}publicSubject getSubject() {returnsubject;

}public voidsetSubject(Subject subject) {this.subject =subject;

}public intgetScore() {returnscore;

}public void setScore(intscore) {this.score =score;

}publicDate getExamDate() {returnexamDate;

}public voidsetExamDate(Date examDate) {this.examDate =examDate;

}

}

9.映射文件

Student.hbm.xml

Subject.hbm.xml

Result.hbm.xml

10.测试

public classHibernateTest {/*** 生成数据库表的工具方法

**/@Testpublic voidtestCreateDB(){

Configuration cfg= newConfiguration().configure();

SchemaExport se= newSchemaExport(cfg);//第一个参数 是否打印sql脚本//第二个参数 是否将脚本导出到数据库中执行

se.create(true, true);

}/*** 初始化表数据*/@Testpublic voidtestInit(){

Session session= null;

Transaction tx= null;try{

SimpleDateFormat df= new SimpleDateFormat("yyyy-MM-dd");

session=HibernateUtil.getSession();

tx=session.beginTransaction();

Student stu1= new Student("张三疯",150);

Student stu2= new Student("张无忌",15);

Subject sub1= new Subject("太极拳");

Subject sub2= new Subject("乾坤大罗移");

Result r1= new Result(stu1, sub1,100,df.parse("1990-08-12"));

Result r2= new Result(stu1, sub2,0,df.parse("1990-08-13"));

Result r3= new Result(stu2, sub1,98,df.parse("1990-08-14"));

Result r4= new Result(stu2, sub2,90,df.parse("1990-08-14"));

session.save(stu1);

session.save(stu2);

session.save(sub1);

session.save(sub2);

session.save(r1);

session.save(r2);

session.save(r3);

session.save(r4);

tx.commit();

}catch(Exception e) {if(tx!=null)

tx.rollback();

}finally{

HibernateUtil.close();

}

}/**

*/@Testpublic voidtestGetData(){

Session session=HibernateUtil.getSession();/*Student stu = (Student)session.get(Student.class, 1);

Subject sub = (Subject)session.get(Subject.class, 1);

Result result = new Result(stu, sub);

result = (Result)session.get(Result.class, result);*/List list = session.createCriteria(Result.class).list();for(Result result:list)

System.out.println(result.getStudent().getName()+"----"+result.getSubject().getName()+"----"+result.getScore());

HibernateUtil.close();

}

}

这里:注释掉的部分是取单个值,而下面的是取列表

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:数字20 设计师:CSDN官方博客 返回首页
评论

打赏作者

weixin_39989973

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值