• 二、Hibernate进阶


    1、many-to-one 关联映射
    2、one-to-many 关联映射
      概述:取出one一方的时候也要取出many一方
      基础:
        t_order(t_id,...)
        t_item(t_id,...,t_order_id)
      需求:
        操作Order的时候一般要操作Item
      基本配置:
        class Order{  
          Set<Item> items;
        }
        Order.hbm.xml
          <set name="items" cascade="all-delete-orphan" inverse="true" lazy="false" fetch="join">
            <key column="t_order_id"/>
            <one-to-many class="Item">
          </set>
      基本操作:
        保存Order同时关联保存Item
          此处为级联操作,所以在set中加入属性cascade="save-update"
          因为保存Item的时候需要先有Order对象,所以就有了many-to-one需求
          所以在Order对象中加入 private Order order;
          在Item.hbm.xml中加入<many-to-one name="order" class="Order" column="t_order_id">
          在Order.hbm.xml中加入inverse="true"是为了让many一方Item来维护,one一方Order不维护,就不会在保存数据时有多余的更新操作
        删除Order
          为了级联删除Item,则需设置Cascade="delete"
        更新Order
          Order中解除了和一个Item的关系,希望在数据库中删除对应记录,<set...cascade="delete-orphan"/>或<set...cascade="all-delete-orphan"/>
        查询Order,同时取出Item
          因为笛卡儿积,所以需要考虑重复的问题
          select distinct(o) from Order o join fetch o.items
          查询包含特定Item的Order
          select distinct(o) from Order o join fetch o.items i where i.productName=".."
        查询Order中包含Item的数目
          formula="(select count(*) from t_item i where i.t_order_id=t_id)"
    3、many-to-many 关联映射
      概述:Student-Course(三张表两个映射文件)由t_student_course维护关系
      基础:
        t_student(t_id,...)
        t_course(t_id,...)
        t_student_course(t_id,t_student_id,t_course_id)
      需求:
        操作Student的时候一般要操作Course
        操作Course的时候一般要操作Student
      基本配置:
        Class Student{
          private Set<Course> courses;
        }
        Student.hbm.xml:
        <set name="courses" table="t_student_course">
          <key column="t_student_course"/>
          <many-to-many class="Course" column="t_course_id"/>
        </set>
    4、继承关联映射
       概述:product-book-computer(三张表同一个映射文件) join-subclass
    5、组合映射
       概述:Question-ChoiceQuestion-EssayQuestion(同一张表) discriminator-subclass
    6、component映射
    person-Address(city+street) 两张表同一映射文件 component

  • 相关阅读:
    Django基础(一)
    CSS
    HTML
    python之路_面向对象
    python之路第六篇
    python之路第四篇
    python之路第三篇
    python之路第二篇
    python之路第一篇
    hdu 3551(一般图的匹配)
  • 原文地址:https://www.cnblogs.com/tombsky/p/3753919.html
Copyright © 2020-2023  润新知