组合主键映射

来源:互联网 发布:js动态创建对象 编辑:程序博客网 时间:2024/05/17 01:56

组合主键映射是指主键是多列的组合,因为考虑到数据库的优化,现在在设计数据库时很少使用。

组合主键映射需要在映射配置文件中使用<composite-id>标签,该标签是指将一个类指定为相应的组合主键,它的name属性需要指定类文件中定义的属性值,并且在该标签中添加<key-property>子标签。

注:组合主键的使用其实很简单,但需要注意对象需要被拆分,主键自己需要一个类并且该类需要实现java.io.Serializable接口,其他属性再重新生成新的类,并且类的属性中要有主键类对象,相应的只需要一个配置文件,在映射文件中使用<composite-id>指明主键,并指明主键的属性。

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

public class ScoreId implements Serializable{private int stuId;private int subjectId;public int getStuId() {return stuId;}public void setStuId(int stuId) {this.stuId = stuId;}public int getSubjectId() {return subjectId;}public void setSubjectId(int subjectId) {this.subjectId = subjectId;}}
2、在主类中引用对应组件

public class Score {private ScoreId scoreId;private double result;//分数public ScoreId getScoreId() {return scoreId;}public void setScoreId(ScoreId scoreId) {this.scoreId = scoreId;}public double getResult() {return result;}public void setResult(double result) {this.result = result;}}
3、配置文件的编写

<hibernate-mapping package="com.test.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" /></class></hibernate-mapping>
4、测试代码

public class HibernateTest {@Testpublic void testCreateDB(){Configuration cfg=new Configuration().configure();SchemaExport se=new SchemaExport(cfg);//第一个参数表示是否生成ddl脚本,第二个参数表示是否执行到数据库中se.create(true, true);}/** * 保存数据 */@Testpublic void save(){Session session=null;Transaction tx=null;try{session=HibernateUtil.getSession();tx=session.beginTransaction();Score s=new Score();ScoreId sid=new ScoreId();sid.setStuId(2);sid.setSubjectId(6);s.setResult(89);s.setScoreId(sid);session.save(s);tx.commit();}catch(Exception e){if(tx!=null)tx.rollback();e.printStackTrace();}finally{HibernateUtil.closeSession();}}}
执行testCreateDB会在控制台打印如下信息:


执行save会在控制台打印如下信息:









原创粉丝点击