search
HomeDatabaseMysql TutorialHibernate关联映射

Hibernate关联映射

Jun 07, 2016 pm 02:49 PM
hibernateassociationdevelopmappingprocessgatherneed

集合映射 开发流程: 需求分析/数据库设计、项目设计/ 编码/测试/实施部署上线/验收需求: 用户购买, 填写地址! // javabean设计 public class User { private int userId; private String userName; // 一个用户,对应的多个地址 private Set String addre

集合映射

<code>开发流程:
    需求分析/数据库设计、项目设计/ 编码/测试/实施部署上线/验收

需求:
    用户购买, 填写地址!
</code>
<code class=" hljs lasso"><span class="hljs-comment">// javabean设计</span>
<span class="hljs-keyword">public</span> class User {

    <span class="hljs-keyword">private</span> int userId;
    <span class="hljs-keyword">private</span> <span class="hljs-built_in">String</span> userName;
    <span class="hljs-comment">// 一个用户,对应的多个地址</span>
    <span class="hljs-keyword">private</span> <span class="hljs-built_in">Set</span><span class="hljs-subst"><</span><span class="hljs-built_in">String</span><span class="hljs-subst">></span> address;
    <span class="hljs-keyword">private</span> <span class="hljs-built_in">List</span><span class="hljs-subst"><</span><span class="hljs-built_in">String</span><span class="hljs-subst">></span> addressList <span class="hljs-subst">=</span> <span class="hljs-literal">new</span> ArrayList<span class="hljs-subst"><</span><span class="hljs-built_in">String</span><span class="hljs-subst">></span>(); 
    <span class="hljs-comment">//private String[] addressArray; // 映射方式和list一样     <array name=""></array></span>
    <span class="hljs-keyword">private</span> <span class="hljs-built_in">Map</span><span class="hljs-subst"><</span><span class="hljs-built_in">String</span>,<span class="hljs-built_in">String</span><span class="hljs-subst">></span> addressMap <span class="hljs-subst">=</span> <span class="hljs-literal">new</span> HashMap<span class="hljs-subst"><</span><span class="hljs-built_in">String</span>, <span class="hljs-built_in">String</span><span class="hljs-subst">></span>();

}
</code>
<code class=" hljs xml"><span class="hljs-comment"><!-- 映射文件 --></span>
<span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.a_collection"</span>></span>

    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"User"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_user"</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"userId"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"id"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">generator</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"native"</span>></span><span class="hljs-tag"></<span class="hljs-title">generator</span>></span>
        <span class="hljs-tag"></<span class="hljs-title">id</span>></span>   
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"userName"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>

        <span class="hljs-comment"><!-- 
            set集合属性的映射
                name 指定要映射的set集合的属性
                table 集合属性要映射到的表
                key  指定集合表(t_address)的外键字段
                element 指定集合表的其他字段
                    type 元素类型,一定要指定
         --></span>
         <span class="hljs-tag"><<span class="hljs-title">set</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"address"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_address"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">key</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"uid"</span>></span><span class="hljs-tag"></<span class="hljs-title">key</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">element</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"address"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"string"</span>></span><span class="hljs-tag"></<span class="hljs-title">element</span>></span>
         <span class="hljs-tag"></<span class="hljs-title">set</span>></span>

         <span class="hljs-comment"><!-- 
            list集合映射
                list-index  指定的是排序列的名称 (因为要保证list集合的有序)
          --></span>
          <span class="hljs-tag"><<span class="hljs-title">list</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"addressList"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_addressList"</span>></span>
              <span class="hljs-tag"><<span class="hljs-title">key</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"uid"</span>></span><span class="hljs-tag"></<span class="hljs-title">key</span>></span>
              <span class="hljs-tag"><<span class="hljs-title">list-index</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"idx"</span>></span><span class="hljs-tag"></<span class="hljs-title">list-index</span>></span>
              <span class="hljs-tag"><<span class="hljs-title">element</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"address"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"string"</span>></span><span class="hljs-tag"></<span class="hljs-title">element</span>></span>
          <span class="hljs-tag"></<span class="hljs-title">list</span>></span>

          <span class="hljs-comment"><!-- 
            map集合的映射
                key  指定外键字段
                map-key 指定map的key 
                element  指定map的value
           --></span>
          <span class="hljs-tag"><<span class="hljs-title">map</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"addressMap"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_addressMap"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">key</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"uid"</span>></span><span class="hljs-tag"></<span class="hljs-title">key</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">map-key</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"shortName"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"string"</span> ></span><span class="hljs-tag"></<span class="hljs-title">map-key</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">element</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"address"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"string"</span> ></span><span class="hljs-tag"></<span class="hljs-title">element</span>></span>
          <span class="hljs-tag"></<span class="hljs-title">map</span>></span>         
    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>
<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span></code>
<code class="language-java hljs ">    <span class="hljs-comment">// 测试程序</span>
    <span class="hljs-comment">// 保存set</span>
    <span class="hljs-annotation">@Test</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testSaveSet</span>() <span class="hljs-keyword">throws</span> Exception {
        Session session = sf.openSession();
        session.beginTransaction();

        <span class="hljs-comment">//-- 保存</span>
        Set<String> addressSet = <span class="hljs-keyword">new</span> HashSet<String>();
        addressSet.add(<span class="hljs-string">"广州"</span>);
        addressSet.add(<span class="hljs-string">"深圳"</span>);
        <span class="hljs-comment">// 用户对象</span>
        User user = <span class="hljs-keyword">new</span> User();
        user.setUserName(<span class="hljs-string">"Jack"</span>);
        user.setAddress(addressSet);

        <span class="hljs-comment">// 保存</span>
        session.save(user);

        session.getTransaction().commit();
        session.close();
    }

    <span class="hljs-comment">// 保存list/map</span>
    <span class="hljs-annotation">@Test</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testSaveList</span>() <span class="hljs-keyword">throws</span> Exception {
        Session session = sf.openSession();
        session.beginTransaction();
        User user = <span class="hljs-keyword">new</span> User();
        user.setUserName(<span class="hljs-string">"Tom"</span>);
<span class="hljs-comment">//      // 用户对象  --  list</span>
<span class="hljs-comment">//      user.getAddressList().add("广州");</span>
<span class="hljs-comment">//      user.getAddressList().add("深圳");</span>
<span class="hljs-comment">//      // 保存</span>
<span class="hljs-comment">//      session.save(user);</span>

        <span class="hljs-comment">// 用户对象  --  Map</span>
        user.getAddressMap().put(<span class="hljs-string">"A0001"</span>, <span class="hljs-string">"广州"</span>);
        user.getAddressMap().put(<span class="hljs-string">"A0002"</span>, <span class="hljs-string">"深圳"</span>);

        <span class="hljs-comment">// 保存</span>
        session.save(user);

        session.getTransaction().commit();
        session.close();
    }
</code>
<code>问题:
    集合映射,映射的集合元素,都是普通的类型, 能否为对象类型?
</code>

关联映射

<code>需求1:
    部门与员工
          一个部门有多个员工;       【一对多】
          多个员工,属于一个部门    【多对一】
需求2:
    项目与开发员工
        一个项目,有多个开发人员!
        一个开发人员,参与多个项目!   【多对多】
</code>

多对一映射与一对多

<code>1. 需求:员工与部门
2. 数据库:
3. 设计javabean封装:
4. 映射:
</code>

这里写图片描述

JavaBean

<code class=" hljs cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Dept {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> deptId;
    <span class="hljs-keyword">private</span> String deptName;
    <span class="hljs-comment">// 【一对多】 部门对应的多个员工</span>
    <span class="hljs-keyword">private</span> Set<Employee> emps = <span class="hljs-keyword">new</span> HashSet<Employee>();
}   
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Employee {

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> empId;
    <span class="hljs-keyword">private</span> String empName;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">double</span> salary;
    <span class="hljs-comment">// 【多对一】员工与部门</span>
    <span class="hljs-keyword">private</span> Dept dept;
}</code>

Dept.hbm.xml

<code class=" hljs xml"><span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.b_one2Many"</span>></span>

    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"Dept"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_dept"</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"deptId"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">generator</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"native"</span>></span><span class="hljs-tag"></<span class="hljs-title">generator</span>></span>
        <span class="hljs-tag"></<span class="hljs-title">id</span>></span>   
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"deptName"</span> <span class="hljs-attribute">length</span>=<span class="hljs-value">"20"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>

        <span class="hljs-comment"><!-- 
            一对多关联映射配置  (通过部门管理到员工)
            Dept 映射关键点:
            1.  指定 映射的集合属性: "emps"
            2.  集合属性对应的集合表: "t_employee"
            3.  集合表的外键字段   "t_employee. dept_id"
            4.  集合元素的类型

         --></span>
         <span class="hljs-tag"><<span class="hljs-title">set</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"emps"</span>></span>   <span class="hljs-comment"><!-- table="t_employee" --></span>
             <span class="hljs-tag"><<span class="hljs-title">key</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"dept_id"</span>></span><span class="hljs-tag"></<span class="hljs-title">key</span>></span>
             <span class="hljs-tag"><<span class="hljs-title">one-to-many</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"Employee"</span>/></span>
         <span class="hljs-tag"></<span class="hljs-title">set</span>></span>      
    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>
<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span></code>

Employee.hbm.xml

<code class=" hljs xml"><span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.b_one2Many"</span>></span>

    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"Employee"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_employee"</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"empId"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">generator</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"native"</span>></span><span class="hljs-tag"></<span class="hljs-title">generator</span>></span>
        <span class="hljs-tag"></<span class="hljs-title">id</span>></span>   
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"empName"</span> <span class="hljs-attribute">length</span>=<span class="hljs-value">"20"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"salary"</span> <span class="hljs-attribute">type</span>=<span class="hljs-value">"double"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>

        <span class="hljs-comment"><!-- 
            多对一映射配置
            Employee 映射关键点:
            1.  映射的部门属性  :  dept
            2.  映射的部门属性,对应的外键字段: dept_id
            3.  部门的类型
         --></span>
         <span class="hljs-tag"><<span class="hljs-title">many-to-one</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"dept"</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"dept_id"</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"Dept"</span>></span><span class="hljs-tag"></<span class="hljs-title">many-to-one</span>></span>       
    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>
<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span></code>

测试

<code class=" hljs java">
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">App</span> {</span>

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> SessionFactory sf;
    <span class="hljs-keyword">static</span> {
        sf = <span class="hljs-keyword">new</span> Configuration()
            .configure()
            .addClass(Dept.class)   
            .addClass(Employee.class)   <span class="hljs-comment">// 测试时候使用</span>
            .buildSessionFactory();
    }

    <span class="hljs-comment">// 保存, 部门方 【一的一方法操作】</span>
    <span class="hljs-annotation">@Test</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">save</span>() {

        Session session = sf.openSession();
        session.beginTransaction();

        <span class="hljs-comment">// 部门对象</span>
        Dept dept = <span class="hljs-keyword">new</span> Dept();
        dept.setDeptName(<span class="hljs-string">"应用开发部"</span>);
        <span class="hljs-comment">// 员工对象</span>
        Employee emp_zs = <span class="hljs-keyword">new</span> Employee();
        emp_zs.setEmpName(<span class="hljs-string">"张三"</span>);
        Employee emp_ls = <span class="hljs-keyword">new</span> Employee();
        emp_ls.setEmpName(<span class="hljs-string">"李四"</span>);
        <span class="hljs-comment">// 关系</span>
        dept.getEmps().add(emp_zs);
        dept.getEmps().add(emp_ls);

        <span class="hljs-comment">// 保存</span>
        session.save(emp_zs);
        session.save(emp_ls);
        session.save(dept); <span class="hljs-comment">// 保存部门,部门下所有的员工  </span>

        session.getTransaction().commit();
        session.close();
        <span class="hljs-comment">/*
         *  结果
         *  Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
            Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
            Hibernate: insert into t_dept (deptName) values (?)
            Hibernate: update t_employee set deptId=? where empId=?    维护员工引用的部门的id
            Hibernate: update t_employee set deptId=? where empId=?
         */</span>
    }
    <span class="hljs-comment">// 【推荐】 保存, 部员方 【多的一方法操作】</span>
    <span class="hljs-annotation">@Test</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">save2</span>() {

        Session session = sf.openSession();
        session.beginTransaction();

        <span class="hljs-comment">// 部门对象</span>
        Dept dept = <span class="hljs-keyword">new</span> Dept();
        dept.setDeptName(<span class="hljs-string">"综合部"</span>);
        <span class="hljs-comment">// 员工对象</span>
        Employee emp_zs = <span class="hljs-keyword">new</span> Employee();
        emp_zs.setEmpName(<span class="hljs-string">"张三"</span>);
        Employee emp_ls = <span class="hljs-keyword">new</span> Employee();
        emp_ls.setEmpName(<span class="hljs-string">"李四"</span>);
        <span class="hljs-comment">// 关系</span>
        emp_zs.setDept(dept);
        emp_ls.setDept(dept);


        <span class="hljs-comment">// 保存</span>
        session.save(dept); <span class="hljs-comment">// 先保存一的方法</span>
        session.save(emp_zs);
        session.save(emp_ls);<span class="hljs-comment">// 再保存多的一方,关系回自动维护(映射配置完)</span>

        session.getTransaction().commit();
        session.close();
        <span class="hljs-comment">/*
         *  结果
         *  Hibernate: insert into t_dept (deptName) values (?)
            Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
            Hibernate: insert into t_employee (empName, salary, dept_id) values (?, ?, ?)
            少生成2条update  sql
         */</span>
    }
}</code>

总结

<code>  在一对多与多对一的关联关系中,保存数据最好的通过多的一方来维护关系,这样可以减少update语句的生成,从而提高hibernate的执行效率!

配置一对多与多对一,这种叫“双向关联”
只配置一对多,           叫“单项一对多”
只配置多对一,           叫“单项多对一”

注意:
    配置了哪一方,哪一方才有维护关联关系的权限!
</code>

Inverse属性

<code>Inverse属性,是在维护关联关系的时候起作用的。
       表示控制权是否转移。(在一的一方起作用)

Inverse , 控制反转。
Inverse = false  不反转;   当前方有控制权
        True  控制反转; 当前方没有控制权

维护关联关系中,是否设置inverse属性:

    1. 保存数据 
        有影响。
       如果设置控制反转,即inverse=true, 然后通过部门方维护关联关系。在保存部门的时候,同时保存员工, 数据会保存,但关联关系不会维护。即外键字段为NULL
</code>

这里写图片描述

<code>    2. 获取数据
        无。
    3. 解除关联关系?
        有影响。
        inverse=false,  可以解除关联
        inverse=true,  当前方(部门)没有控制权,不能解除关联关系
        (不会生成update语句,也不会报错)
    4. 删除数据对关联关系的影响?
        有影响。
        inverse=false, 有控制权, 可以删除。先清空外键引用,再删除数据。
        inverse=true,  没有控制权: 如果删除的记录有被外键引用,会报错,违反主外键引用约束!  如果删除的记录没有被引用,可以直接删除。
</code>

cascade 属性

<code>cascade  表示级联操作  【可以设置到一的一方或多的一方】
    none                  不级联操作, 默认值
    save-update           级联保存或更新
    delete                级联删除
    save-update,delete    级联保存、更新、删除
    all                   同上。级联保存、更新、删除
</code>

多对多映射

<code>需求:项目与开发人员
      Project   Developer
      电商系统
           曹吉
           王春
       OA系统
            王春
            老张
</code>

这里写图片描述

JavaBean

<code class=" hljs cs"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Developer {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> d_id;
    <span class="hljs-keyword">private</span> String d_name;
    <span class="hljs-comment">// 开发人员,参数的多个项目</span>
    <span class="hljs-keyword">private</span> Set<Project> projects = <span class="hljs-keyword">new</span> HashSet<Project>();
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> Project {
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> prj_id;
    <span class="hljs-keyword">private</span> String prj_name;
    <span class="hljs-comment">// 项目下的多个员工</span>
    <span class="hljs-keyword">private</span> Set<Developer> developers = <span class="hljs-keyword">new</span> HashSet<Developer>();
}</code>

Project.hbm.xml

<code class=" hljs xml"><span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.c_many2many"</span>></span>

    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"Project"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_project"</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"prj_id"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">generator</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"native"</span>></span><span class="hljs-tag"></<span class="hljs-title">generator</span>></span>
        <span class="hljs-tag"></<span class="hljs-title">id</span>></span>   
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"prj_name"</span> <span class="hljs-attribute">length</span>=<span class="hljs-value">"20"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>
        <span class="hljs-comment"><!-- 
            多对多映射:
            1.  映射的集合属性: “developers”
            2.  集合属性,对应的中间表: “t_relation”
            3. 外键字段:  prjId
            4. 外键字段,对应的中间表字段:  did
            5.   集合属性元素的类型
         --></span>
         <span class="hljs-tag"><<span class="hljs-title">set</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"developers"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_relation"</span> <span class="hljs-attribute">cascade</span>=<span class="hljs-value">"save-update"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">key</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"prjId"</span>></span><span class="hljs-tag"></<span class="hljs-title">key</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">many-to-many</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"did"</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"Developer"</span>></span><span class="hljs-tag"></<span class="hljs-title">many-to-many</span>></span>
         <span class="hljs-tag"></<span class="hljs-title">set</span>></span>      
    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>
<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span></code>

Developer.hbm.xml

<code class=" hljs xml"><span class="hljs-pi"><?xml version="1.0"?></span>
<span class="hljs-doctype"><!DOCTYPE hibernate-mapping PUBLIC 
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"></span>

<span class="hljs-tag"><<span class="hljs-title">hibernate-mapping</span> <span class="hljs-attribute">package</span>=<span class="hljs-value">"cn.itcast.c_many2many"</span>></span>

    <span class="hljs-tag"><<span class="hljs-title">class</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"Developer"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_developer"</span>></span>
        <span class="hljs-tag"><<span class="hljs-title">id</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"d_id"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">generator</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"native"</span>></span><span class="hljs-tag"></<span class="hljs-title">generator</span>></span>
        <span class="hljs-tag"></<span class="hljs-title">id</span>></span>   
        <span class="hljs-tag"><<span class="hljs-title">property</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"d_name"</span> <span class="hljs-attribute">length</span>=<span class="hljs-value">"20"</span>></span><span class="hljs-tag"></<span class="hljs-title">property</span>></span>

        <span class="hljs-comment"><!-- 
            多对多映射配置: 员工方
                name  指定映射的集合属性
                table 集合属性对应的中间表
                key   指定中间表的外键字段(引用当前表t_developer主键的外键字段)
                many-to-many
                    column 指定外键字段对应的项目字段
                    class  集合元素的类型
         --></span>
        <span class="hljs-tag"><<span class="hljs-title">set</span> <span class="hljs-attribute">name</span>=<span class="hljs-value">"projects"</span> <span class="hljs-attribute">table</span>=<span class="hljs-value">"t_relation"</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">key</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"did"</span>></span><span class="hljs-tag"></<span class="hljs-title">key</span>></span>
            <span class="hljs-tag"><<span class="hljs-title">many-to-many</span> <span class="hljs-attribute">column</span>=<span class="hljs-value">"prjId"</span> <span class="hljs-attribute">class</span>=<span class="hljs-value">"Project"</span>></span><span class="hljs-tag"></<span class="hljs-title">many-to-many</span>></span>
        <span class="hljs-tag"></<span class="hljs-title">set</span>></span>       
    <span class="hljs-tag"></<span class="hljs-title">class</span>></span>
<span class="hljs-tag"></<span class="hljs-title">hibernate-mapping</span>></span></code>

维护关联关系

<code>设置inverse属性,在多对多种维护关联关系的影响?

1) 保存数据
    有影响。
    inverse=false ,有控制权,可以维护关联关系; 保存数据的时候会把对象关系插入中间表;
    inverse=true,  没有控制权, 不会往中间表插入数据。

2) 获取数据
    无。

3) 解除关系
    有影响。
    inverse=false ,有控制权, 解除关系就是删除中间表的数据。
    inverse=true, 没有控制权,不能解除关系。

4) 删除数据
    有影响。
    inverse=false, 有控制权。 先删除中间表数据,再删除自身。
    inverse=true, 没有控制权。 如果删除的数据有被引用,会报错! 否则,才可以删除
</code>
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)