hibernate教程笔记8
级联cascade操作,
当进行某个操作(crud create read update delete)由hibernate自动帮你完成
比如,Department<->Student 当删除一个department对象后,删除该部门的所有学生。
比如,主贴<->回贴 当删除主贴,所有回贴随之删除。
级联cascade。
级联删除
<set name="stus" cascade="delete">
Hibernate: select department0_.id as id0_0_, department0_.name as name0_0_ from Department department0_ where department0_.id=?
Hibernate: select stus0_.dept_id as dept3_1_, stus0_.id as id1_, stus0_.id as id1_0_, stus0_.name as name1_0_, stus0_.dept_id as dept3_1_0_ from Student stus0_ where stus0_.dept_id=?
Hibernate: select dept_seq.nextval from dual
Hibernate: select stu_seq.nextval from dual
Hibernate: select stu_seq.nextval from dual
Hibernate: insert into Department (name, id) values (?, ?)
Hibernate: insert into Student (name, dept_id, id) values (?, ?, ?)
Hibernate: insert into Student (name, dept_id, id) values (?, ?, ?)Hibernate: select department0_.id as id0_0_, department0_.name as name0_0_ from Department department0_ where department0_.id=?
Hibernate: select stus0_.dept_id as dept3_1_, stus0_.id as id1_, stus0_.id as id1_0_, stus0_.name as name1_0_, stus0_.dept_id as dept3_1_0_ from Student stus0_ where stus0_.dept_id=?
Hibernate: select department0_.id as id0_0_, department0_.name as name0_0_ from Department department0_ where department0_.id=?
Hibernate: select stus0_.dept_id as dept3_1_, stus0_.id as id1_, stus0_.id as id1_0_, stus0_.name as name1_0_, stus0_.dept_id as dept3_1_0_ from Student stus0_ where stus0_.dept_id=?
Hibernate: update Student set dept_id=null where dept_id=?
Hibernate: delete from Student where id=?
Hibernate: delete from Student where id=?
Hibernate: delete from Department where id=?
级联添加
<set name="stus" cascade="save-update">
Hibernate: select dept_seq.nextval from dual
Hibernate: select stu_seq.nextval from dual
Hibernate: select stu_seq.nextval from dual
Hibernate: insert into Department (name, id) values (?, ?)
Hibernate: insert into Student (name, dept_id, id) values (?, ?, ?)
Hibernate: insert into Student (name, dept_id, id) values (?, ?, ?)
Hibernate: update Student set dept_id=? where id=?
Hibernate: update Student set dept_id=? where id=?
完整的测试项目
package com.qq.view;
import com.qq.util.*;
import com.qq.domain.*;import org.hibernate.Session;
import org.hibernate.Transaction;import java.util.HashSet;
import java.util.List;
import java.util.Iterator;
import java.util.Set;
import org.hibernate.Query;
public class TestMain {private static Session session=null;private static Transaction ts=null;public static void main(String[] args){Session session=null;Transaction tx=null;try {//获取一个session加载hibernate.cfg.xml创建数据库//HibernateUtil.openSession();session=HibernateUtil.getCurrentSession();tx=session.beginTransaction();//法1//String hql="from Student where dept.id=1";//法2// Department department=(Department)session.get(Department.class, 3);// Set<Student> stus=department.getStus();// for(Student ss:stus){// System.out.println(ss.getName());// }/*//添加学生Department d1=new Department();d1.setName("水利部");Student stu1=new Student();stu1.setName("张辽");stu1.setDept(d1);Student stu2=new Student();stu2.setName("赵子龙");stu2.setDept(d1);session.save(d1);session.save(stu1);session.save(stu2);*//*//演示级联删除Department d=(Department)session.get(Department.class, 7);session.delete(d);*///级联添加
// 添加学生Department d1=new Department();d1.setName("水利部");Student stu1=new Student();stu1.setName("张涛");stu1.setDept(d1);Student stu2=new Student();stu2.setName("赵敏");stu2.setDept(d1);//保存部门的同时保存学生// session.save(stu1);// session.save(stu2);Set<Student> stus=new HashSet<Student>();stus.add(stu1);stus.add(stu2);d1.setStus(stus);session.save(d1);tx.commit();//提交后会自动关闭session} catch (Exception e) {// TODO: handle exceptione.printStackTrace();if(tx!=null){tx.rollback();new RuntimeException(e.getMessage());}}finally{if(session!=null && session.isOpen()){session.close();}}}}
同样可以在Student.hbm.xml配置<many-to-one name="dept" column="dept_id" cascade="save-update"/>
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC"-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration><session-factory><property name="connection.username">scott</property><property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property><property name="dialect">org.hibernate.dialect.Oracle9Dialect</property><property name="connection.password">tiger</property><property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property><property name="show_sql">true</property><!-- 配置 自动创建关系模型 --><property name="hbm2ddl.auto">update</property><mapping resource="com/qq/domain/Department.hbm.xml" /><mapping resource="com/qq/domain/Student.hbm.xml" /></session-factory></hibernate-configuration>
一般cascade配置在one-to-many 中one的地方,即主对象的地方。
package com.qq.domain;public class Student implements java.io.Serializable{private static final long serialVersionUID=1L;private Integer id;private String name;private Department dept;public Department getDept() {return dept;}public void setDept(Department dept) {this.dept = dept;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain"><class name="Student"><id name="id" type="java.lang.Integer"><generator class="sequence"><param name="sequence">stu_seq</param></generator> </id><property name="name" type="java.lang.String"><column name="name" length="64"/></property><!-- 对于private Department dept就不能用property来配置了 将来自动生成的外键名dept_id--><many-to-one name="dept" column="dept_id"/></class>
</hibernate-mapping>
package com.qq.domain;
import java.util.Set;
public class Department implements java.io.Serializable{private static final long serialVersionUID=1L;private Integer id;private String name;private Set<Student> stus;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Set<Student> getStus() {return stus;}public void setStus(Set<Student> stus) {this.stus = stus;}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping package="com.qq.domain"><class name="Department"><id name="id" type="java.lang.Integer"><generator class="sequence"><param name="sequence">dept_seq</param></generator></id><property name="name" type="java.lang.String"><column name="name" length="64" not-null="true"/></property><!-- 配置one to many关系 stus是Department.java中的属性名称,Student是类名--><!-- 删除部门,部门学生随之删除 --><set name="stus" cascade="save-update"><!-- 指定Student类对应的外键 dept_id是Student.hbm.xml中指定的外键名称--><key column="dept_id"/><one-to-many class="Student"/></set></class>
</hibernate-mapping>
package com.qq.util;
import java.util.List;import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
final public class HibernateUtil {private static SessionFactory sessionFactory=null;//使用线程局部模式private static ThreadLocal<Session> threadLocal=new ThreadLocal<Session>();private HibernateUtil(){};static {sessionFactory=new Configuration().configure().buildSessionFactory();}//获取全新的全新的sesessionpublic static Session openSession(){return sessionFactory.openSession();}//获取和线程关联的sessionpublic static Session getCurrentSession(){Session session=threadLocal.get();//判断是否得到if(session==null){session=sessionFactory.openSession();//把session对象设置到 threadLocal,相当于该session已经和线程绑定threadLocal.set(session);}return session;}public static void closeCurrentSession(){Session s=getCurrentSession();if(s!=null&& s.isOpen() ){s.close();threadLocal.set(null);}}//这里提供一个根据id返回对象的方法public static Object findById(Class clazz,java.io.Serializable id){Session s=null;Transaction tx=null;Object obj=null;try {s=openSession();tx=s.beginTransaction();obj=s.load(clazz, id);tx.commit();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());// TODO: handle exception}finally{if(s!=null&&s.isOpen()){s.close();}}return obj;}//统一的一个修改和删除(批量 hql) hql"delete upate ...??"public static void executeUpdate(String hql,String [] parameters){Session s=null;Transaction tx=null;try {s=openSession();tx=s.beginTransaction();Query query=s.createQuery(hql);//先判断是否有参数要绑定if(parameters!=null&& parameters.length>0){for(int i=0;i<parameters.length;i++){query.setString(i, parameters[i]);}}query.executeUpdate();tx.commit();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());// TODO: handle exception}finally{if(s!=null&&s.isOpen()){s.close();}}}//如果要配置openSessionInView//统一的一个修改和删除(批量 hql) hql"delete upate ...??"public static void executeUpdateOpenInView(String hql,String [] parameters){Session s=getCurrentSession();Query query=s.createQuery(hql);//先判断是否有参数要绑定if(parameters!=null&& parameters.length>0){for(int i=0;i<parameters.length;i++){query.setString(i, parameters[i]);}}query.executeUpdate();}//统一的添加的方法public static void save(Object obj){Session s=null;Transaction tx=null;try {s=openSession();tx=s.beginTransaction();s.save(obj);tx.commit();} catch (Exception e) {if(tx!=null){tx.rollback();}throw new RuntimeException(e.getMessage());// TODO: handle exception}finally{if(s!=null && s.isOpen()){s.close();}}}//提供一个统一的查询方法(带分页) hql 形式 from 类 where 条件=? ..public static List executeQueryByPage(String hql,String [] parameters,int pageSize,int pageNow){Session s=null;List list=null;try {s=openSession();Query query=s.createQuery(hql);//先判断是否有参数要绑定if(parameters!=null&& parameters.length>0){for(int i=0;i<parameters.length;i++){query.setString(i, parameters[i]);}}query.setFirstResult((pageNow-1)*pageSize).setMaxResults(pageSize);list=query.list();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());// TODO: handle exception}finally{if(s!=null&&s.isOpen()){s.close();}}return list;}//提供一个统一的查询方法 hql 形式 from 类 where 条件=? ..public static List executeQuery(String hql,String [] parameters){Session s=null;List list=null;try {s=openSession();Query query=s.createQuery(hql);//先判断是否有参数要绑定if(parameters!=null&& parameters.length>0){for(int i=0;i<parameters.length;i++){query.setString(i, parameters[i]);}}list=query.list();} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e.getMessage());// TODO: handle exception}finally{if(s!=null&&s.isOpen()){s.close();}}return list;}}
hibernate教程笔记8相关推荐
- Hibernate学习笔记(一)----针对不同的数据库不同的配置
Hibernate初学笔记 l Hibernate初步配置: 1 新建项目 2 学习建立user-library-hibernate,并加入相应的jar包(hibernate核心jar包,lib下的所 ...
- hibernate学习笔记二
上一篇关于hibernate学习笔记一,主要是作为hibernate的入门知识.没有和spring发生任何关系,这一篇我将把spring集成进去,看spring如何管理hibernate,还有和未使用 ...
- 台湾国立大学郭彦甫Matlab教程笔记(22) Cramer's method(Inverse matrix逆矩阵法)
台湾国立大学郭彦甫Matlab教程笔记(22) Cramer's method(Inverse matrix) matrix left division左除:\ or mldivide() solvi ...
- 台湾国立大学郭彦甫Matlab教程笔记(21)linear equations(高斯消去法和追赶法)
台湾国立大学郭彦甫Matlab教程笔记(21) today: linear equation 线性方程 linear system 线性系统 我们先看第一部分 linear equation 假定一个 ...
- 台湾国立大学郭彦甫Matlab教程笔记(20) root finding(numeric)
台湾国立大学郭彦甫Matlab教程笔记(20) root finding(numeric) symbolic vs. numeric符号法和数值法的区别对比 symbolic 1)advantages ...
- 台湾国立大学郭彦甫Matlab教程笔记(17)numerical integration
台湾国立大学郭彦甫Matlab教程笔记(17)numerical integration 数值积分 calculating the numerical value of a definite inte ...
- 台湾国立大学郭彦甫Matlab教程笔记(16) 数值微分 numerical differentiation
台湾国立大学郭彦甫Matlab教程笔记(16) 数值微分 numeric differentiation 复习:diff()函数用来计算vector前后 entry的差异 数值微分继续 various ...
- 台湾国立大学郭彦甫Matlab教程笔记(15)polynomial integration 多项式积分
台湾国立大学郭彦甫Matlab教程笔记(15) Polynomial integration多项式积分 一个多项式和它的积分如下 MATlAB中如何计算积分? polynomial integrati ...
- 台湾国立大学郭彦甫Matlab教程笔记(14)polynomial differentiation多项式微分
台湾国立大学郭彦甫Matlab教程笔记(14) today: polynomial differentiation and integration多项式微分与积分 numerical differen ...
- 台湾国立大学郭彦甫Matlab教程笔记(12) advanced 2D plot 下
台湾国立大学郭彦甫Matlab教程笔记(12) advanced 2D plot 下 上文记录的是关于统计的图标的绘制 下面我们来到另一个模块:颜色 fill()填充函数 功能:某一个封闭曲线,图上特 ...
最新文章
- 橡皮筋进度条ElasticProgressBar
- linux移植会话层层协议,Linux内核移植-南京林业大学毕业设计.DOC
- clion phpstorm 等jetbrains编辑器激活教程
- go语言游戏编程-Ebiten实现画面的填充
- 基于pygame的射击小游戏制作(一)让飞船动起来
- 计算机网络 闯关,2009计算机网络考研试题过关必练.docx
- Angular开发模式下的编译器和运行时的代码比较
- 如何看当前windows是utf8还是gbk_监理工程师5月份出教材,现在如何备考?
- TensorFlow 教程 --进阶指南--3.9TensorBoard: 图表可视化
- linux命令-p,Linux-send命令详解
- 基恩士光纤传感器怎么恢复出厂设置_光纤故障排查测试必备神器
- 量子计算(四):量子力学的发展史
- MongoDB 极简实践入门
- 五粮液前三季净赚173亿背后:Q3净利增速下滑,3大流通股东减持
- java基础—输入/输出
- Java中的Constants类
- IDEA集成Java性能分析神器JProfiler
- python使用qq邮箱发邮件
- linux dd 硬盘克隆,如何使用Linux dd命令克隆磁盘
- Windows下的MySQL实例没有mysql.user表#Olivia丶长歌#