持久化对象,即就是在数据库中存有其相对应数据的对象,并且在内存中也有这个对象,这个对象在Session的管理范围内,也就是调用过save()方法同步到数据库的对象。
瞬时对象,即在内存中刚刚创建的对象,还没有同步到数据库,或者是数据库中信息被删除了的对象也是临时状态。
游离对象,也就是在数据库中有和该对象向对应的纪录,并且在内存中的也存在该对象,但是不在Session的管理范围之内,也就是在Session关闭之后,就成了游离对象,就不会在将其改变同步到数据库中,如果要使还想令其成为持久化对象就要在把它纳入Session管理中,也就是掉用Session中的update()方法就可以了。
及物的持久化,也就是说针对这个对象的属性进行持久化操作,也就是通过级联进行设置。
一对多
建表策略,多方引用一方的主键当作外键
以经典的班级和学生为例,Clazz类(由于Class是类类的名字不能使用)和Student类
学生类Student
package alan.hbn.o2m;
import java.io.Serializable;
public class Student implements Serializable{
private int studentId;
private String studentName;
private Clazz clazz;
public void setStudentId(int studentId){
this.studentId = studentId;
}
public int getStudentId(){
return this.studentId;
}
public void setStudentName(String studentName){
this.studentName = studentName;
}
public String getStudentName(){
return this.studentName;
}
public Class getClazz(){
return this.clazz;
}
public void setClazz(Clazz clazz){
this.clazz=clazz;
}
}
班级类Clazz
package alan.hbn.rel.o2m;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Clazz implements Serializable{
private int clazzId;
private String clazzname;
private Set<Student> students = new HashSet<Student>();
public int getClazzId(){
return clazzId;
}
public void setClazzId(int clazzId){
this.clazzId = clazzId;
}
public String getClazzname(){
return clazzname;
}
public void setClazzname(String clazzname){
this.clazzname =clazzname;
}
public Set getStudents(){
return students;
}
public void setStudents(Set<Student> Students){
this.students = students;
}
public void addStudent(Student student){
students.add(student);
if(student!= null){
student.setClazz(this);
}
}
}
一对多的映射配置文件
Student类的映射配置文件 Student.hbm.xml
<hibernate-mapping package="alan.hbn.o2m">
<class name="Student" table="student">
<id name="studentId" column="studentId">
<generator class="native"/>
</id>
<property name="studentName" column="studentName"/>
<many-to-one name="clazz" class="Clazz" column="classid"
not-null="true" fetch="join"/>
<!--
many-to-one标签name属性是表示本类中关联类的对象的名字,class属性表示其类型,column属性是表示引用外键的字段名
-->
</class>
</hibernate-mapping>
Clazz类的映射配置文件Clazz.hbm.xml
<hibernate-mapping package="alan.hbn.rel.o2m" >
<class name="Clazz" table="class_o2m">
<id name="clazzId" column="classid">
<generator class="native"/>
</id>
<property name="clazzname" column="classname"/>
<set name="students" inverse="true" cascade="save-update">
<key column="classid"/>
<one-to-many class="Student"/>
</set>
<!--
set标签对应的是本类中的集合属性,set标签的自标签key是标明本类对应的表中被引用为外键的字段,one-to-many标签是标明关联的类型,也就是集合属性中存放的类型
-->
</class>
</hibernate-mapping>