一 cascade属性
当设置了cascade属性不为none时,Hibernate会自动持久化所关联的对象。
cascade属性的设置会带来性能上的变动,需谨慎设置。
二 配置级联属性
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping>
<class name="com.imooc.entity.Grade" table="grade">
<id name="gid" column="gid" type="java.lang.Integer">
<generator class="increment"></generator>
</id>
<property name="gname" type="java.lang.String">
<column name="gname" length="20" not-null="true"></column>
</property>
<property name="gdesc">
<column name="gdesc"></column>
</property>
<!-- 配置一对多关联关系 ,设置inverse属性未true,由多方来维护关联关系-->
<!--当进行保存和更新时,级联操作关联的对象-->
<set name="students" table="student" inverse="true" cascade="save-update">
<key column="gid"></key>
<one-to-many class="com.imooc.entity.Student"/>
</set>
</class>
</hibernate-mapping>
三 测试代码
package com.imooc.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.imooc.entity.Grade;
import com.imooc.entity.Student;
import com.imooc.util.HibernateUtil;
/*
* 单向多对一(学生--->班级)
*/
public class Test02 {
public static void main(String[] args) {
save();
}
//保存
public static void save(){
Grade g=new Grade("Java一班","Java软件开发一班");
Student stu1=new Student("慕女神", "女");
Student stu2=new Student("小慕慕", "男");
//设置关联关系
g.getStudents().add(stu1);
g.getStudents().add(stu2);
stu1.setGrade(g);
stu2.setGrade(g);
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
session.save(g);//级联操作,保存了班级,会级联保存学生,不需要下面两句话
// session.save(stu1);
// session.save(stu2);
tx.commit();
HibernateUtil.closeSession(session);
}
}
四 测试结果
Hibernate: select max(gid) from grade
Hibernate: select max(sid) from student
Hibernate: insert into grade (gname, gdesc, gid) values (?, ?, ?)
Hibernate: insert into student (sname, sex, gid, sid) values (?, ?, ?, ?)
Hibernate: insert into student (sname, sex, gid, sid) values (?, ?, ?, ?)