SSH框架之Hibernate的表操作(三)

2019-03-27  本文已影响0人  Seapp

第一节:数据库表与表之间的关系

1.1 一对多关系

1.2 多对多关系

1.3 一对一关系(了解)

第二节:Hibernate中一对多表之间映射关系的建立

2.1 创建数据库和表

SQL语句如下:

//客户信息,一
CREATE TABLE `cst_customer` (
  `cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '客户编号(主键)',
  `cust_name` varchar(32) NOT NULL COMMENT '客户名称(公司名称)',
  `cust_source` varchar(32) DEFAULT NULL COMMENT '客户信息来源',
  `cust_industry` varchar(32) DEFAULT NULL COMMENT '客户所属行业',
  `cust_level` varchar(32) DEFAULT NULL COMMENT '客户级别',
  `cust_phone` varchar(64) DEFAULT NULL COMMENT '固定电话',
  `cust_mobile` varchar(16) DEFAULT NULL COMMENT '移动电话',
  PRIMARY KEY (`cust_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
//联系人信息:多
CREATE TABLE `cst_linkman` (
  `lkm_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '联系人编号(主键)',
  `lkm_name` varchar(16) DEFAULT NULL COMMENT '联系人姓名',
  `lkm_cust_id` bigint(32) DEFAULT NULL COMMENT '客户id',
  `lkm_gender` char(1) DEFAULT NULL COMMENT '联系人性别',
  `lkm_phone` varchar(16) DEFAULT NULL COMMENT '联系人办公电话',
  `lkm_mobile` varchar(16) DEFAULT NULL COMMENT '联系人手机',
  `lkm_email` varchar(64) DEFAULT NULL COMMENT '联系人邮箱',
  `lkm_qq` varchar(16) DEFAULT NULL COMMENT '联系人qq',
  `lkm_position` varchar(16) DEFAULT NULL COMMENT '联系人职位',
  `lkm_memo` varchar(512) DEFAULT NULL COMMENT '联系人备注',
  PRIMARY KEY (`lkm_id`),
  KEY `FK_cst_linkman_lkm_cust_id` (`lkm_cust_id`),
  CONSTRAINT `FK_cst_linkman_lkm_cust_id` FOREIGN KEY (`lkm_cust_id`) REFERENCES `cst_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
一对多表的对应关系

2.2 创建实体类与映射类

package com.seapp.hibernate.domain;

import java.util.HashSet;
import java.util.Set;

public class Customer {

    private Long cust_id;
    private String cust_name;
    private String cust_source;
    private String cust_industry;
    private String cust_level;
    private String cust_phone;
    private String cust_mobile;

    //通过ORM方式表示,一个客户对应多个联系人
    //放置的多的一方的集合,Hibernate默认使用的是set集合
    private Set<LinkMan> linkMans = new HashSet<>();

    public Customer() {
    }

    public Long getCust_id() {
        return cust_id;
    }

    public void setCust_id(Long cust_id) {
        this.cust_id = cust_id;
    }

    public String getCust_name() {
        return cust_name;
    }

    public void setCust_name(String cust_name) {
        this.cust_name = cust_name;
    }

    public String getCust_source() {
        return cust_source;
    }

    public void setCust_source(String cust_source) {
        this.cust_source = cust_source;
    }

    public String getCust_industry() {
        return cust_industry;
    }

    public void setCust_industry(String cust_industry) {
        this.cust_industry = cust_industry;
    }

    public String getCust_level() {
        return cust_level;
    }

    public void setCust_level(String cust_level) {
        this.cust_level = cust_level;
    }

    public String getCust_phone() {
        return cust_phone;
    }

    public void setCust_phone(String cust_phone) {
        this.cust_phone = cust_phone;
    }

    public String getCust_mobile() {
        return cust_mobile;
    }

    public void setCust_mobile(String cust_mobile) {
        this.cust_mobile = cust_mobile;
    }

    public Set<LinkMan> getLinkMans() {
        return linkMans;
    }

    public void setLinkMans(Set<LinkMan> linkMans) {
        this.linkMans = linkMans;
    }

    @Override
    public String toString() {
        return "Customer{" +
                "cust_id=" + cust_id +
                ", cust_name='" + cust_name + '\'' +
                ", cust_source='" + cust_source + '\'' +
                ", cust_industry='" + cust_industry + '\'' +
                ", cust_level='" + cust_level + '\'' +
                ", cust_phone='" + cust_phone + '\'' +
                ", cust_mobile='" + cust_mobile + '\'' +
                '}';
    }
}

Customer.hbm.xml映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <!--建立一个类与表之间的映射关系-->
    <!--
         class标签:用来建立类和表的映射
            * name属性:类中的全路径。
            * table属性:表名(如果类名和表名是一致的,那么table属性可以省略)
            * catalog属性:数据库名称,可以商量
    -->
    <class name="com.seapp.hibernate.domain.Customer" table="cst_customer">
        <!--建立类中属性与表中主键字段的对象关系-->
        <!--
            id标签:用来建立类中的属性与表中的主键字段对应
            * name属性   :类中的属性名
            * column属性 :表中字段名(如果类中属性名和表中字段名是一致的,那么column属性可以省略)
            * length属性 :字段的长度
            * type属性   :类型。
        -->
        <id name="cust_id" column="cust_id">
            <!--主键生成策略-->
            <!--
            * increment:Hibernate中提供的自动增长的机制,适用于long,short或int类型的主键。在单线程中使用,
                在集群下不要使用(存在线程安全的问题);
            * identity:适用于short,int,long类型的主键,使用的是数据库底层的自动增长机制,适用于有自动增
                长机制的数据库(MySql,MSSQL),Oracle不适用。
            * sequence:适用于short,int,long类型的主键,采用的是序列的方式。Oracle支持。
            * uuid:适用于字符串类型的主键,使用hibernate中的随机方式生成字符串主键。
            * native:本地策略,可以在identity和sequence之间自动切换。
            * assigned:hibernate放弃主键的管理,需要用户自行设定
            * foreigen:使用另外一个相关联的对象的标识符。它通常和 <one-to-one> 联合起来使用。
            -->
            <generator class="native"/>
        </id>
        <!--建立类中普通属性与表中字段的映射关系-->
        <!--
            property标签:用来建立类中普通属性与表中字段的对应
            * name属性    :类中的属性名
            * column属性  :表中字段名(如果类中的属性名与表中的字段名一致,则该属性可以省略)
            * length属性  :字段的长度
            * type属性    :类型
        -->
        <property name="cust_name" column="cust_name"/>
        <property name="cust_source" column="cust_source"/>
        <property name="cust_industry" column="cust_industry"/>
        <property name="cust_level" column="cust_level"/>
        <property name="cust_phone" column="cust_phone"/>
        <property name="cust_mobile" column="cust_mobile"/>

        <!--配置关联对象-->
        <!--
         set 标签:
            * name属性:多的一方集合的属性名称
        -->
        <set name="linkMans">
            <!--
            key标签:
                * clumn :多的一方的外键名称
            -->
            <key column="lkm_cust_id"></key>
            <!--
             one-to-many标签:
                * class 属性:多的一方的全路径
            -->
            <one-to-many class="com.seapp.hibernate.domain.LinkMan"/>
        </set>
    </class>
</hibernate-mapping>

使用set集合来描述Customer.java类中的属性linkMans。在Hibernate的映射文件中,使用<set>标签来描述被映射类中的Set集合,<key>标签的column属性值对应文件多的一方的外键名称。在Customer.java客户类中,客户与联系人是一对多的关系,Hibernatede的映射文件中,使用<one-to-many>标签来描述持久化类的一对多关联,其中class属性用来描述映射的关联类。

package com.seapp.hibernate.domain;

/**
 * 联系人的实体类
 */
public class LinkMan {

    /*
    `lkm_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '联系人编号(主键)',
    `lkm_name` varchar(16) DEFAULT NULL COMMENT '联系人姓名',
    `lkm_cust_id` bigint(32) DEFAULT NULL COMMENT '客户id',
    `lkm_gender` char(1) DEFAULT NULL COMMENT '联系人性别',
    `lkm_phone` varchar(16) DEFAULT NULL COMMENT '联系人办公电话',
    `lkm_mobile` varchar(16) DEFAULT NULL COMMENT '联系人手机',
    `lkm_email` varchar(64) DEFAULT NULL COMMENT '联系人邮箱',
    `lkm_qq` varchar(16) DEFAULT NULL COMMENT '联系人qq',
    `lkm_position` varchar(16) DEFAULT NULL COMMENT '联系人职位',
    `lkm_memo` varchar(512) DEFAULT NULL COMMENT '联系人备注',
    */

    private Long lkm_id;
    private String lkm_name;
    private Long lkm_cust_id;
    private Integer lkm_gender;
    private String lkm_phone;
    private String lkm_mobile;
    private String lkm_email;
    private String lkm_qq;
    private String lkm_position;
    private String lkm_memo;

    //通过ORM方式表示,一个联系人只能属于一个客户。
    //放置的是一的一方的对象
    private Customer customer;

    public LinkMan() {
    }

    public Long getLkm_id() {
        return lkm_id;
    }

    public void setLkm_id(Long lkm_id) {
        this.lkm_id = lkm_id;
    }

    public String getLkm_name() {
        return lkm_name;
    }

    public void setLkm_name(String lkm_name) {
        this.lkm_name = lkm_name;
    }

    public Long getLkm_cust_id() {
        return lkm_cust_id;
    }

    public void setLkm_cust_id(Long lkm_cust_id) {
        this.lkm_cust_id = lkm_cust_id;
    }

    public Integer getLkm_gender() {
        return lkm_gender;
    }

    public void setLkm_gender(Integer lkm_gender) {
        this.lkm_gender = lkm_gender;
    }

    public String getLkm_phone() {
        return lkm_phone;
    }

    public void setLkm_phone(String lkm_phone) {
        this.lkm_phone = lkm_phone;
    }

    public String getLkm_mobile() {
        return lkm_mobile;
    }

    public void setLkm_mobile(String lkm_mobile) {
        this.lkm_mobile = lkm_mobile;
    }

    public String getLkm_email() {
        return lkm_email;
    }

    public void setLkm_email(String lkm_email) {
        this.lkm_email = lkm_email;
    }

    public String getLkm_qq() {
        return lkm_qq;
    }

    public void setLkm_qq(String lkm_qq) {
        this.lkm_qq = lkm_qq;
    }

    public String getLkm_position() {
        return lkm_position;
    }

    public void setLkm_position(String lkm_position) {
        this.lkm_position = lkm_position;
    }

    public String getLkm_memo() {
        return lkm_memo;
    }

    public void setLkm_memo(String lkm_memo) {
        this.lkm_memo = lkm_memo;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    @Override
    public String toString() {
        return "LinkMan{" +
                "lkm_id=" + lkm_id +
                ", lkm_name='" + lkm_name + '\'' +
                ", lkm_cust_id=" + lkm_cust_id +
                ", lkm_gender=" + lkm_gender +
                ", lkm_phone='" + lkm_phone + '\'' +
                ", lkm_mobile='" + lkm_mobile + '\'' +
                ", lkm_email='" + lkm_email + '\'' +
                ", lkm_qq='" + lkm_qq + '\'' +
                ", lkm_position='" + lkm_position + '\'' +
                ", lkm_memo='" + lkm_memo + '\'' +
                '}';
    }
}

LinkMan.hbm.xml映射文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <!--建立类与表之间的映射关系-->
    <class name="com.seapp.hibernate.domain.LinkMan" table="cst_linkman">
        <!--主键的对应关系-->
        <id name="lkm_id" column="lkm_id">
            <!--主键的生成策略-->
            <generator class="native"/>
        </id>

        <!--类中普通属性的对应关系-->
        <property name="lkm_name" column="lkm_name"/>
        <!--<property name="lkm_cust_id" column="lkm_cust_id"/>-->
        <property name="lkm_gender" column="lkm_gender"/>
        <property name="lkm_phone" column="lkm_phone"/>
        <property name="lkm_mobile" column="lkm_mobile"/>
        <property name="lkm_email" column="lkm_email"/>
        <property name="lkm_qq" column="lkm_qq"/>
        <property name="lkm_position" column="lkm_position"/>
        <property name="lkm_memo" column="lkm_memo"/>

        <!--配置关联对象-->
        <!--
        many-to-one 标签:
            * name属性:一的一方的对象的名称
            * class属性:一的一方类的全路径
            * column属性:表中的外键的名称
        -->
        <many-to-one
                name="customer"
                class="com.seapp.hibernate.domain.Customer"
                column="lkm_cust_id"/>

    </class>

</hibernate-mapping>

<many-to-one>标签定义了两个持久化类的关联,这种关联是数据表间的多对一关联,联系人与客户就是多对一的关系,所以用<many-to-one>标签来描述。<many-to-one>标签的name属性用来描述customer在LinkMan.java类中的属性的名称,class属性用来指定映射的类,column属性对应表中的外键列名。

    @Test
    /**
     * 一对多练习
     */
    public void demo02(){

        Session currentSission = HibernateUtil.getCurrentSission();
        Transaction transaction = currentSission.beginTransaction();

        //1。创建个客户
        Customer customer01 = new Customer();
        customer01.setCust_name("练习王");
        //2。创建对应的联系人信息
        LinkMan linkMan01 = new LinkMan();
        linkMan01.setLkm_name("王子一");

        LinkMan linkMan02 = new LinkMan();
        linkMan02.setLkm_name("王子二");
        //3。建立具体人员之间的联系关系
        Set<LinkMan> linkMans = customer01.getLinkMans();
        linkMans.add(linkMan01);
        linkMans.add(linkMan02);
        linkMan01.setCustomer(customer01);
        linkMan02.setCustomer(customer01);
        currentSission.save(customer01);
        currentSission.save(linkMan01);
        currentSission.save(linkMan02);

        //4.进行事务的提交
        transaction.commit();
    }

测试过程中Hibernate执行的语句:

Hibernate: 
    insert 
    into
        cst_customer
        (cust_name, cust_source, cust_industry, cust_level, cust_phone, cust_mobile) 
    values
        (?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        cst_linkman
        (lkm_name, lkm_gender, lkm_phone, lkm_mobile, lkm_email, lkm_qq, lkm_position, lkm_memo, lkm_cust_id) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        cst_linkman
        (lkm_name, lkm_gender, lkm_phone, lkm_mobile, lkm_email, lkm_qq, lkm_position, lkm_memo, lkm_cust_id) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate: 
    update
        cst_linkman 
    set
        lkm_cust_id=? 
    where
        lkm_id=?
Hibernate: 
    update
        cst_linkman 
    set
        lkm_cust_id=? 
    where
        lkm_id=?

Process finished with exit code 0

以上的代码我们可以发现建立关系是双向的,即客户关联了联系人,同时联系人也关联了客户。接下来做这么个测试,既然我们已经建立了双向的维护关系,那么我们只保存客户或只保存联系人是否可以将数据保存成功呢?

测试代码如下

 @Test
    public void demo2(){
        Session currentSission = HibernateUtil.getCurrentSission();
        Transaction transaction = currentSission.beginTransaction();

        //1.建立客户
        Customer customer = new Customer();
        customer.setCust_name("王百万");
        //2.建立联系人
        LinkMan linkMan01 = new LinkMan();
        linkMan01.setLkm_name("张千万");
        LinkMan linkMan02 = new LinkMan();
        linkMan02.setLkm_name("李千万");
        //4.双向联系关系的维护
        customer.getLinkMans().add(linkMan01);
        customer.getLinkMans().add(linkMan02);
        linkMan01.setCustomer(customer);
        linkMan02.setCustomer(customer);
        //5.进行数据保存
        currentSission.save(customer);

        transaction.commit();
    }

异常信息如下:

java.lang.IllegalStateException: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.seapp.hibernate.domain.LinkMan

    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:151)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:188)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1490)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:515)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3355)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2526)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:178)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$300(JdbcResourceLocalTransactionCoordinatorImpl.java:39)
    at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:271)
    at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:104)
    at com.seapp.hibernate.test.HibernateDemo02.demo2(HibernateDemo02.java:71)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.seapp.hibernate.domain.LinkMan
    at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:350)
    at org.hibernate.type.EntityType.getIdentifier(EntityType.java:495)
    at org.hibernate.type.EntityType.nullSafeSet(EntityType.java:280)
    at org.hibernate.persister.collection.AbstractCollectionPersister.writeElement(AbstractCollectionPersister.java:926)
    at org.hibernate.persister.collection.AbstractCollectionPersister.recreate(AbstractCollectionPersister.java:1349)
    at org.hibernate.persister.collection.OneToManyPersister.recreate(OneToManyPersister.java:186)
    at org.hibernate.action.internal.CollectionRecreateAction.execute(CollectionRecreateAction.java:50)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1484)
    ... 31 more

这样操作显然不行,无论从那一方保存都会出现同样的异常:瞬时对象异常,一个持久态对象关联了一个瞬时态对象。那如果我们想只保存一个方向应该如何操作呢,从而引入Hibernate的级联操作

第三节:Hiberanate的级联操作

级联操作是指当主控方执行保存、更新或者删除操作时,其关联对象(被控方)也执行相同的操作。在映射文件中通过对cascade属性的设置来控制是否对关联对象采用级联操作。级联操作对各种关联关系都是有效的。

级联是有方向性的,所谓的方向性指的是,在保存一的一方级联多的一方和在保存多的一方级联一的一方。配置cascade后,操作其中一方则关联一方也执行相应的操作。


image.png

级联查询

@Test
    //导航查询
    public void findTest(){
        Session currentSission = HibernateUtil.getCurrentSission();
        Transaction transaction = currentSission.beginTransaction();

        Customer customer = currentSission.load(Customer.class, 6L);
        System.out.println(customer.toString());


        transaction.commit();

    }

查询结果:

Hibernate: 
    select
        customer0_.cust_id as cust_id1_0_0_,
        customer0_.cust_name as cust_nam2_0_0_,
        customer0_.cust_source as cust_sou3_0_0_,
        customer0_.cust_industry as cust_ind4_0_0_,
        customer0_.cust_level as cust_lev5_0_0_,
        customer0_.cust_phone as cust_pho6_0_0_,
        customer0_.cust_mobile as cust_mob7_0_0_ 
    from
        cst_customer customer0_ 
    where
        customer0_.cust_id=?
Hibernate: 
    select
        linkmans0_.lkm_cust_id as lkm_cus10_1_0_,
        linkmans0_.lkm_id as lkm_id1_1_0_,
        linkmans0_.lkm_id as lkm_id1_1_1_,
        linkmans0_.lkm_name as lkm_name2_1_1_,
        linkmans0_.lkm_gender as lkm_gend3_1_1_,
        linkmans0_.lkm_phone as lkm_phon4_1_1_,
        linkmans0_.lkm_mobile as lkm_mobi5_1_1_,
        linkmans0_.lkm_email as lkm_emai6_1_1_,
        linkmans0_.lkm_qq as lkm_qq7_1_1_,
        linkmans0_.lkm_position as lkm_posi8_1_1_,
        linkmans0_.lkm_memo as lkm_memo9_1_1_,
        linkmans0_.lkm_cust_id as lkm_cus10_1_1_ 
    from
        cst_linkman linkmans0_ 
    where
        linkmans0_.lkm_cust_id=?
Customer{cust_id=6, cust_name='王百万', cust_source='null', cust_industry='null', cust_level='null', cust_phone='null', cust_mobile='null', linkMans=[LinkMan{lkm_id=6, lkm_name='张千万', lkm_cust_id=null, lkm_gender=null, lkm_phone='null', lkm_mobile='null', lkm_email='null', lkm_qq='null', lkm_position='null', lkm_memo='null'}, LinkMan{lkm_id=5, lkm_name='李千万', lkm_cust_id=null, lkm_gender=null, lkm_phone='null', lkm_mobile='null', lkm_email='null', lkm_qq='null', lkm_position='null', lkm_memo='null'}]}

Process finished with exit code 0

第四节:双向关联产生多余的SQL语句的问题解决

因为双向维护了关系,而且持久态对象可以自动更新数据库,更改客户的时候会修改一次外键,更新联系人的时候同样也会修改一次外键。这样就会产生多余的SQL,那么如何解决呢?
其实解决额方法很简单:只需要将一方放弃外键维护权即可 。也就是说关系不是双方维护的,只需要交给某一方去维护就可以了。通常我们都是交给多的一方去维护的,为什么呢?因为多的一方才是维护关系最好的地方。举个例子:一个老师对应多个学生,一个学生对应多个老师,这是典型的一对多,那么一个老师如果要记住所有学生的名字很难,但如果让每个学生记住老师的名字应该不难。其实就是这个道理。所以在一对多中,一的一方都会放弃对外界的维护权(关系的维护)。
如果想让一的一方放弃外键的维护权,只需要进行如下的配置:

image.png
inverse的默认值是false,代表不放弃对外键的维护权,配置值为true,代表放弃了外键的维护权。

第五节:Hibernate中多对多映射关系的建立。

用户表

CREATE TABLE `sys_user` (
  `user_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `user_code` varchar(32) DEFAULT NULL COMMENT '用户账号',
  `user_name` varchar(64) DEFAULT NULL COMMENT '用户名称',
  `user_password` varchar(32) DEFAULT NULL COMMENT '用户密码',
  `user_state` char(1) DEFAULT NULL COMMENT '1:正常,0:暂停',
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

角色表:

CREATE TABLE `sys_role` (
  `role_id` bigint(32) NOT NULL AUTO_INCREMENT,
  `role_name` varchar(32) NOT NULL COMMENT '角色名称',
  `role_memo` varchar(128) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`role_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

中间表:

CREATE TABLE `sys_user_role` (
  `role_id` bigint(32) NOT NULL COMMENT '角色id',
  `user_id` bigint(32) NOT NULL COMMENT '用户id',
  PRIMARY KEY (`role_id`,`user_id`),
  KEY `FK_user_role_user_id` (`user_id`),
  CONSTRAINT `FK_user_role_role_id` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`role_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `FK_user_role_user_id` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
package com.seapp.hibernate.domain;

import java.util.HashSet;
import java.util.Set;

/**
 * user实体类
 */
public class User {

    private Long user_id;
    private String user_code;
    private String user_name;
    private String user_password;
    private String user_state;

    private Set<Role> roles = new HashSet<>();

    public Long getUser_id() {
        return user_id;
    }

    public void setUser_id(Long user_id) {
        this.user_id = user_id;
    }

    public String getUser_code() {
        return user_code;
    }

    public void setUser_code(String user_code) {
        this.user_code = user_code;
    }

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getUser_password() {
        return user_password;
    }

    public void setUser_password(String user_password) {
        this.user_password = user_password;
    }

    public String getUser_state() {
        return user_state;
    }

    public void setUser_state(String user_state) {
        this.user_state = user_state;
    }

    public Set<Role> getRoles() {
        return roles;
    }

    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
}
 /************************Hibernate中User的映射表**********************************/
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.seapp.hibernate.domain.User" table="sys_user">
        <!--主键的配置-->
        <id name="user_id" column="user_id">
            <generator class="native"/>
        </id>
        <!--基本属性的配置-->
        <property name="user_code" column="user_code"/>
        <property name="user_name" column="user_name"/>
        <property name="user_password" column="user_password"/>
        <property name="user_state" column="user_state"/>
        <!--
        set属性:
            name:关联的另一方的集合的名称
            table: 中间表的名称
        -->
        <set name="roles" table="sys_user_role">
            <!--
           key属性:
               * column:当前对象对应中间表中的外键的名称
           -->
            <key column="user_id"></key>
            <!--
           many-to-many属性:
               *class:对应对象类的全路径
               *column:对应对象在中间表中的外键名称
           -->
            <many-to-many class="com.seapp.hibernate.domain.Role" column="role_id"></many-to-many>
        </set>


    </class>

</hibernate-mapping>

 /**********************************************************/

package com.seapp.hibernate.domain;

import java.util.HashSet;
import java.util.Set;

/**
 * 角色实体类
 */
public class Role {

    private Long role_id;
    private String role_name;
    private String role_memo;

    private Set<User> users = new HashSet<>();


    public Long getRole_id() {
        return role_id;
    }

    public void setRole_id(Long role_id) {
        this.role_id = role_id;
    }

    public String getRole_name() {
        return role_name;
    }

    public void setRole_name(String role_name) {
        this.role_name = role_name;
    }

    public String getRole_memo() {
        return role_memo;
    }

    public void setRole_memo(String role_memo) {
        this.role_memo = role_memo;
    }

    public Set<User> getUsers() {
        return users;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }
}

 /*************************Hibernate中role的映射关系*********************************/
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>

    <class name="com.seapp.hibernate.domain.Role" table="sys_role">
        <!--主键的配置-->
        <id name="role_id" column="role_id">
            <generator class="native"/>
        </id>

        <!--基本属性的配置-->
        <property name="role_name" column="role_name"/>
        <property name="role_memo" column="role_memo"/>
        <!--
         set标签:
             *name:关联的另一方的集合的名称
             *table: 中间表的名称
             *inverse:在建立双向联系时,被动方放弃对主键的维护权
         -->
        <set name="users" table="sys_user_role" inverse="true">
            <!--
            key属性:
                * column:当前对象对应中间表中的外键的名称
            -->
            <key column="role_id"></key>
            <!--
            many-to-many属性:
                *class:对应对象类的全路径
                *column:对应对象在中间表中的外键名称
            -->
            <many-to-many class="com.seapp.hibernate.domain.User" column="user_id"></many-to-many>
        </set>

    </class>

</hibernate-mapping>

在多对多的保存操作中,如果进行了双向维护关系,就必须有一方放弃外键维护权。一般由被动方放弃,用户主动选择角色,角色是被选择的,所以一般角色要放弃外键的维护权。


image.png

之前学习过的一对多的级联保存及删除在多对多中依然生效,通过配置cascade的属性来实现。
多对多的关系主要是靠中间表来维护的,那么在Hibernate中多对多主要是靠关联的集合来维护的,所以在多对多我们只需要关心如何操作集合即可。

上一篇下一篇

猜你喜欢

热点阅读