联合主键的映射运用

1.联合主键的映射规则数据库

1) 类中的每一个主键属性都对应到数据表中的每一个主键列。session

Hibernate要求具备联合主键的实体类实现Serializable接口,而且重写hashCode与equals方法,重写这两个方法的缘由在于Hibernate要根据数据库的联合主键来判断某两行记录是不是同样的,若是同样那么就认为是同一个对象,若是不同,那么就认为是不一样的对象。这反映到程序领域中就是根据hashCode与equals方法来判断某两个对象是否可以放到诸如Set这样的集合当中。联合主键的实体类实现Serializable接口的缘由在于使用get或load方法的时候须要先构建出来该实体的对象,而且将查询依据(联合主键)设置进去,而后做为get或load方法的第二个参数传进去便可。spa

2) 将主键所对应属性提取出一个类(称之为主键类),而且主键类须要实现Serializable接口,重写equals方法与hashCode方法,缘由与上面同样。.net

以Student类为例,实现上述两种映射联合主键的配置:hibernate

2.Student中的两个属性做为联合主键属性xml

Student类:对象

public class Student implements Serializable {//必需要实现Serializable接口blog

private String cardID;//cardID和name映射为联合主键
private String name;
private int age;
//get、set、hashCode、equals方法省略
}接口

 

注:可以使用MyEclipse中的Sourse-->Gennerate hashCode and equals来使用MyEclipse快速生成hashCode和equals方法ip

 Student.hbm.xml配置:

<class name="bean.Student" table="student">
<composite-id><!--联合主键,student表中的主键为(student_name,card_id)-->
<key-property name="name" column="student_name" type="string"></key-property><!--name及cardID为Student类中的属性-->
<key-property name="cardID" column="card_id" type="string"></key-property>
</composite-id>
<property name="age" column="student_age" type="int"></property>
</class>

保存对象:

tx=session.beginTransaction();

Student s1=new Student();
s1.setName("lisi");
s1.setAge(22);
s1.setCardID("711");
System.out.println(s1);
session.save(s1);
tx.commit();

注意:主键为(card_id,student_id)若连续执行上述的保存语句两次,固然会抛异常,应为主键重复:   
           org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
3.将Student类中的两个主键属性提取为一个新的类PrimaryKey,即主键类

 主键类PrimaryKey:

public class PrimaryKey implements Serializable{

private String cardID;
private String name;
//get、set、hashCode、equals方法省略
}

Student类中含有PrimaryKey类型的属性及对应set、get方法:

public class Student {
private int age;
private PrimaryKey primaryKey;
//set、get方法省略
}

Student.hbm.xml文件中的配置:

<class name="bean.Student" table="student">
<composite-id name="primaryKey" class="bean.PrimaryKey"><!--PrimaryKey为咱们自定义的主键类-->
<key-property name="name" column="student_name" type="string"></key-property><!--name及cardID为PrimaryKey类中的属性-->
<key-property name="cardID" column="card_id" type="string"></key-property>
</composite-id>
<property name="age" column="student_age" type="int"></property>
</class>

保存对象:

tx=session.beginTransaction();

Student s1=new Student();
s1.setAge(23);
PrimaryKey p=new PrimaryKey();
p.setCardID("102");
p.setName("zhangsan");
s1.setPrimaryKey(p);
session.save(s1);
tx.commit();

一样,对于上述代码的重复执行也会致使主键重复抛出异常。

查询:

PrimaryKey p=new PrimaryKey();
p.setCardID("711");
p.setName("lisi");
Student s=(Student)session.get(Student.class,p);//因此PrimaryKey要实现Serializable接口
System.out.println(s.getAge());

转载请注明出处:http://blog.csdn.net/jialinqiang/article/details/8704538

相关文章
相关标签/搜索