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 exception
			e.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();
	}
	
	//获取全新的全新的sesession
	public static Session openSession(){
		return sessionFactory.openSession();
	}
	//获取和线程关联的session
	public 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;
	}
	
	
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值