hibernate笔记--组合主键映射方法
一个数据库表中其主键有可能不止一个属性,同样映射到实体类中,可能有两个或多个属性共同配置成为一个主键,假设一个实体类Score,其主键有两个属性stuId(学生编号)和subjectId(科目编号),在hibernate环境下应该这样配置:
新建一个实体类ScoreId,属性为stuId,和subjectId,该类需要实现serializable接口(最好重写equals方法和hashcode方法):
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; } public ScoreId(int stuId, int subjectId) { super(); this.stuId = stuId; this.subjectId = subjectId; } }
新建实体类Score:
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; } public Score(ScoreId scoreId, double result) { super(); this.scoreId = scoreId; this.result = result; } }
其次是Score.hbm.xml配置文件:
<?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="com.wang.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>
hibernate.cfg.xml这里就省略了,现在新建一个测试类,用于生成数据库表以及向数据库中存放一条数据:
@Test public void testCreateDB(){ Configuration cfg = new Configuration().configure(); SchemaExport se=new SchemaExport(cfg); //第一个参数是否生成ddl脚本 第二个参数是否执行到数据库 se.create(true,true); } @Test public void testSave(){ Session session = HibernateUtil.getSession(); Transaction tx = session.beginTransaction(); Score s=new Score(new ScoreId(2,5),88); session.save(s); tx.commit(); session.close(); }