zoukankan      html  css  js  c++  java
  • Hibernate映射一对多单向关联(之三)

    Hibernate映射一对多单向关联(之二)中,可以检索出一个Student所对应的所有课程,放在一个HashSet中。

    如果一个学生的记录被删除了,就应该考虑到它的其他信息也全部删除掉,比如他的全部课程记录。

    将Student.hbm.xml中cascade值设置为如下:

    cascade="all"

    或者

    cascade="all-delete-orphan"

    cascade="all",既能满足我们save-update的需要,又能实现级联delete。cascade="all-delete-orphan",则如果还有很多与Student有关的表,则所有这些表中的记录都会被级联删除掉。

    如果不需要级联存储更新,即save-update,则cascade可以设置为delete。

    假设我们要删除了学号为200802001的Student,同时删除他的所有课程记录。

    测试程序如下:

    package org.shirdrn.test;

    import java.util.List;
    import java.util.Set;

    import org.hibernate.Criteria;
    import org.hibernate.Session;
    import org.hibernate.Transaction;
    import org.hibernate.criterion.Restrictions;
    import org.shirdrn.HibernateSessionFactory;
    import org.shirdrn.entity.Student;

    public class MyTest {
    public static void main(String[] args){
       Session session = HibernateSessionFactory.getSession();
       Transaction tx = null;
       try{
        tx = session.beginTransaction();
        Student dbStu = (Student)session.load(Student.class, "200802001");
        Criteria c = session.createCriteria(Student.class);
        c.add(Restrictions.eq("sno", "200802001"));
          List list = c.list();
          Student stu = (Student)list.get(0);
          Set hsSet = stu.getScs();
          stu.setScs(hsSet);
          session.delete(stu);
          tx.commit();
       }
       catch(Exception e){
        tx.rollback();
        e.printStackTrace();
       }
       finally{
        HibernateSessionFactory.closeSession();
       }
    }

    }

    执行结果:

    Hibernate: select this_.sno as sno0_, this_.sname as sname0_0_, this_.dept as dept0_0_ from student this_ where this_.sno=?
    Hibernate: select scs0_.sno as sno1_, scs0_.cno as cno1_, scs0_.sno as sno0_, scs0_.cno as cno0_, scs0_.cname as cname4_0_, scs0_.score as score4_0_ from sc scs0_ where scs0_.sno=?
    Hibernate: delete from sc where sno=? and cno=?
    Hibernate: delete from sc where sno=? and cno=?
    Hibernate: delete from sc where sno=? and cno=?
    Hibernate: delete from student where sno=?

    大概的过程就是:先检索出Student对应于Sc中的记录,通过Student的对象获取Sc的HashSet记录集,再set到Student的对象中。在删除Student的对象的时候,级联删除了所有对应于该Student的Sc中记录。

    一对多双向关联中,多对一单向关联和Hibernate映射多对一单向关联(之一)Hibernate映射多对一单向关联(之二)是一样的。

    一对多单向关联也可以是一对多双向关联,因为一对多不会产生冗余。

    不像多对一关联,多对一是单向关联,如果多对一双向关联就产生冗余。

  • 相关阅读:
    运动检测技术在数字化监控中的实现和应用(作者:何峻峰)
    EF BB BF的问题
    理解HTTP幂等性
    FusionCharts 分类以及各个属性 参数列表
    SQL语言包含的四个部分
    Inno Setup (安装程序制作)
    PowerDesigner 参照完整性约束(级联删除)
    java默认语法、EL、JSTL表达式,JSTL和struts Tag标签的使用总结
    修改PowerDesigner中create index的bug
    神奇的java Object ( Object和数组关系) Object数据互转
  • 原文地址:https://www.cnblogs.com/a1280055207/p/2856061.html
Copyright © 2011-2022 走看看