美文网首页
Java mac idea hibernate的使用03

Java mac idea hibernate的使用03

作者: 编程_书恨少 | 来源:发表于2018-08-14 11:56 被阅读0次

    1. 一对多和多对一关系

    1.1 模型分析

    Snip20180810_37.png

    1.2 建表

    1. 创建Customer表
    CREATE TABLE `t_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_linkman` VARCHAR(64) 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;
    
    1. 创建LinkMan表
    
    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) NOT 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 `t_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
            ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
    

    1.3 创建与表对应的实体类,描述两者间的关系

    1. 创建Customer类
    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_linkman;
        private String cust_phone;
        private String cust_mobile;
    
        // 使用set集合表达一对多关系
        private Set<LinkMan> linkMen = new HashSet<LinkMan>();
    
        public Set<LinkMan> getLinkMen() {
            return linkMen;
        }
    
        public void setLinkMen(Set<LinkMan> linkMen) {
            this.linkMen = linkMen;
        }
    
        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_linkman() {
            return cust_linkman;
        }
        public void setCust_linkman(String cust_linkman) {
            this.cust_linkman = cust_linkman;
        }
        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;
        }
        @Override
        public String toString() {
            return "Customer [cust_id=" + cust_id + ", cust_name=" + cust_name + "]";
        }
        
    
    1. 创建LinkMan类
    public class LinkMan {
    
        private Long lkm_id;
        private Character lkm_gender;
        private String lkm_name;
        private String lkm_phone;
        private String lkm_email;
        private String lkm_qq;
        private String lkm_mobile;
        private String lkm_memo;
        private String lkm_position;
    
        //表达多对一关系
        private Customer customer ;
    
        public Long getLkm_id() {
            return lkm_id;
        }
    
        public void setLkm_id(Long lkm_id) {
            this.lkm_id = lkm_id;
        }
    
        public Character getLkm_gender() {
            return lkm_gender;
        }
    
        public void setLkm_gender(Character lkm_gender) {
            this.lkm_gender = lkm_gender;
        }
    
        public String getLkm_name() {
            return lkm_name;
        }
    
        public void setLkm_name(String lkm_name) {
            this.lkm_name = lkm_name;
        }
    
        public String getLkm_phone() {
            return lkm_phone;
        }
    
        public void setLkm_phone(String lkm_phone) {
            this.lkm_phone = lkm_phone;
        }
    
        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_mobile() {
            return lkm_mobile;
        }
    
        public void setLkm_mobile(String lkm_mobile) {
            this.lkm_mobile = lkm_mobile;
        }
    
        public String getLkm_memo() {
            return lkm_memo;
        }
    
        public void setLkm_memo(String lkm_memo) {
            this.lkm_memo = lkm_memo;
        }
    
        public String getLkm_position() {
            return lkm_position;
        }
    
        public void setLkm_position(String lkm_position) {
            this.lkm_position = lkm_position;
        }
    
        public Customer getCustomer() {
            return customer;
        }
    
        public void setCustomer(Customer customer) {
            this.customer = customer;
        }
    }
    

    1.4 书写hibernate配置文件

    1. 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 package="domain" >
    
            <class name="Customer" table="t_customer" >
            <!-- id元素:配置主键映射的属性
                    name: 填写主键对应属性名
                    column(可选): 填写表中的主键列名.默认值:列名会默认使用属性名
                    type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
                            每个类型有三种填法: java类型|hibernate类型|数据库类型
                    not-null(可选):配置该属性(列)是否不能为空. 默认值:false
                    length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
             -->
            <id name="cust_id"  >
                <!-- generator:主键生成策略,每条记录录入时,主键的生成规则
                    identity: 主键自增
                 -->
                <generator class="native"></generator>
            </id>
            <!-- property元素:除id之外的普通属性映射
                    name: 填写属性名
                    column(可选): 填写列名
                    type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
                            每个类型有三种填法: java类型|hibernate类型|数据库类型
                    not-null(可选):配置该属性(列)是否不能为空. 默认值:false
                    length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
             -->
                <property name="cust_name" >
                    <!--  <column name="cust_name" sql-type="varchar" ></column> -->
                </property>
                <property name="cust_source"  ></property>
                <property name="cust_industry"  ></property>
                <property name="cust_level" ></property>
                <property name="cust_linkman" ></property>
                <property name="cust_phone"  ></property>
                <property name="cust_mobile"  ></property>
    
                <!-- 一对多关系  -->
                <!--
                    name:集合属性名
                    column:外键列名
                    class:与当前类关联的外键完整类名
                 -->
                <set name="linkMen">
                    <key column="lkm_cust_id"></key>
                    <one-to-many class="LinkMan"/>
                </set>
        </class>
    </hibernate-mapping>
    
    1. 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">
    
       <!-- 配置表与实体对象的关系 -->
    
       <!-- package属性:填写一个包名.在元素内部凡是需要书写完整类名的属性,可以直接写简答类名了. -->
        <hibernate-mapping package="domain" >
        <!-- 
            class元素: 配置实体与表的对应关系的
                name: 完整类名
                table:数据库表名
         -->
            <class name="LinkMan" table="cst_linkman" >
            <!-- id元素:配置主键映射的属性
                    name: 填写主键对应属性名
                    column(可选): 填写表中的主键列名.默认值:列名会默认使用属性名
                    type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
                            每个类型有三种填法: java类型|hibernate类型|数据库类型
                    not-null(可选):配置该属性(列)是否不能为空. 默认值:false
                    length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
             -->
            <id name="lkm_id"  >
                <!-- generator:主键生成策略,每条记录录入时,主键的生成规则
                    identity: 主键自增
                 -->
                <generator class="native"></generator>
            </id>
            <!-- property元素:除id之外的普通属性映射
                    name: 填写属性名
                    column(可选): 填写列名
                    type(可选):填写列(属性)的类型.hibernate会自动检测实体的属性类型.
                            每个类型有三种填法: java类型|hibernate类型|数据库类型
                    not-null(可选):配置该属性(列)是否不能为空. 默认值:false
                    length(可选):配置数据库中列的长度. 默认值:使用数据库类型的最大长度
             -->
                <property name="lkm_gender"  ></property>
                <property name="lkm_phone"  ></property>
            <property name="lkm_name" ></property>
            <property name="lkm_email"  ></property>
            <property name="lkm_qq"></property>
            <property name="lkm_mobile" ></property>
            <property name="lkm_memo"  ></property>
            <property name="lkm_position"  ></property>
    
                <!-- 多对一关系  -->
                <!--
                    name:引用属性名
                    column:外键列名
                    class:与当前类关联的外键完整类名
                 -->
                <many-to-one name="customer" column="lkm_cust_id" class="Customer"></many-to-one>
    
            </class>
    </hibernate-mapping>
    
    1. hibernate.cfg.xml
    <mapping resource="domain/Customer.hbm.xml" />
    <mapping resource="domain/LinkMan.hbm.xml" />
    

    1.5 测试

    public class TestOne2Many {
    
        @Test
        public void testFunc() {
    
            // 1. 获得session
            Session session = HibernateUtils.openSession();
    
            // 2. 开启事务
            Transaction transaction = session.beginTransaction();
    
            // 3.操作
            LinkMan linkMan1 = new LinkMan();
            linkMan1.setLkm_name("maHuaTeng");
    
            LinkMan linkMan2 = new LinkMan();
            linkMan2.setLkm_name("maYun");
    
            Customer customer = new Customer();
            customer.setCust_name("baidu");
    
    
            // 表达一对多
            customer.getLinkMen().add(linkMan1);
            customer.getLinkMen().add(linkMan2);
    
            // 表达多对一
            linkMan1.setCustomer(customer);
            linkMan2.setCustomer(customer);
    
    
            session.save(customer);
    
            session.save(linkMan1);
            session.save(linkMan2);
    
            transaction.commit();
            session.close();
        }
    }
    

    2. 一对多和多对一操作

    2.1 客户添加联系人操作

    @Test
        // 客户添加联系人
        public void testFunc02() {
    
            // 1. 获得session
            Session session = HibernateUtils.openSession();
    
            // 2. 开启事务
            Transaction transaction = session.beginTransaction();
    
            // 3.操作
            // 获得客户
            Customer customer = session.get(Customer.class, 1l);
    
            // 创建联系人
            LinkMan linkMan = new LinkMan();
            linkMan.setLkm_name("maFeiSi");
    
            // 建立一对多关系
            customer.getLinkMen().add(linkMan);
    
            // 建立多对一关系
            linkMan.setCustomer(customer);
    
            session.save(customer);
            session.save(linkMan);
    
    
            transaction.commit();
            session.close();
        }
    

    2.2 客户删除联系人

     @Test
        // 客户删除联系人
        public void testFunc03() {
    
            // 1. 获得session
            Session session = HibernateUtils.openSession();
    
            // 2. 开启事务
            Transaction transaction = session.beginTransaction();
    
            // 3.操作
            // 获得客户
            Customer customer = session.get(Customer.class, 1l);
    
            // 创建联系人
            LinkMan linkMan = session.get(LinkMan.class, 5l);
    
            // 建立一对多关系
            customer.getLinkMen().remove(linkMan);
    
            // 建立多对一关系
            linkMan.setCustomer(null);
    
    
            transaction.commit();
            session.close();
        }
    

    3. 级联操作

    3.1 级联保存

                  <!-- 一对多关系  -->
                <!--
                    cascade:级联操作
                    save-update:级联保存更新
                    delete:级联删除
                    all:save-update + delete
                 -->
                <set name="linkMen" cascade="save-update">
                    <key column="lkm_cust_id"></key>
                    <one-to-many class="LinkMan"/>
                </set>
    
    
     @Test
        // 级联保存
        public void testFunc04() {
    
            // 1. 获得session
            Session session = HibernateUtils.openSession();
    
            // 2. 开启事务
            Transaction transaction = session.beginTransaction();
    
            // 3.操作
            // 获得客户
            Customer customer = new Customer();
            customer.setCust_name("baidu");
    
            // 创建联系人
            LinkMan linkMan1 = new LinkMan();
            linkMan1.setLkm_name("maHuaTeng");
    
            LinkMan linkMan2 = new LinkMan();
            linkMan2.setLkm_name("maYun");
    
            // 建立一对多关系
            customer.getLinkMen().add(linkMan1);
            customer.getLinkMen().add(linkMan2);
    
            // 建立多对一关系
            linkMan1.setCustomer(customer);
            linkMan2.setCustomer(customer);
    
            // 保存
            session.save(customer);
    
            transaction.commit();
            session.close();
        }
    

    3.2 级联删除

    <set name="linkMen" cascade="delete">
                    <key column="lkm_cust_id"></key>
                    <one-to-many class="LinkMan"/>
    
    @Test
        // 级联删除
        public void testFunc05() {
    
            // 1. 获得session
            Session session = HibernateUtils.openSession();
    
            // 2. 开启事务
            Transaction transaction = session.beginTransaction();
    
            // 3.操作
            // 获得客户
            Customer customer = session.get(Customer.class, 1l);
    
            session.delete(customer);
    
            transaction.commit();
            session.close();
        }
    

    3.3 联系人方进行级联保存

    <many-to-one name="customer" column="lkm_cust_id" class="Customer" cascade="save-update">
    </many-to-one>
    
     @Test
        // 级联保存
        public void testFunc06() {
    
            // 1. 获得session
            Session session = HibernateUtils.openSession();
    
            // 2. 开启事务
            Transaction transaction = session.beginTransaction();
    
            // 3.操作
            // 获得客户
            Customer customer = new Customer();
            customer.setCust_name("baidu");
    
            // 创建联系人
            LinkMan linkMan = new LinkMan();
            linkMan.setLkm_name("maHuaTeng");
    
    
            // 建立一对多关系
            customer.getLinkMen().add(linkMan);
    
            // 建立多对一关系
            linkMan.setCustomer(customer);
    
            // 保存
            session.save(linkMan);
    
            transaction.commit();
            session.close();
        }
    

    4. 一对多和多对一进阶

    4.1 inverse属性

    1. 用来过滤掉冗余的sql操作,让多的一方进行外键的维护,一的一方放弃外键的维护。
    一的一方插入数据
    Hibernate: 
        insert 
        into
            t_customer
            (cust_name, cust_source, cust_industry, cust_level, cust_linkman, cust_phone, cust_mobile) 
        values
            (?, ?, ?, ?, ?, ?, ?)
    Hibernate: 
        insert 
        into
            cst_linkman
            (lkm_gender, lkm_phone, lkm_name, lkm_email, lkm_qq, lkm_mobile, lkm_memo, lkm_position, lkm_cust_id) 
        values
            (?, ?, ?, ?, ?, ?, ?, ?, ?)
    Hibernate: 
        insert 
        into
            cst_linkman
            (lkm_gender, lkm_phone, lkm_name, lkm_email, lkm_qq, lkm_mobile, lkm_memo, lkm_position, 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=?
    
    1. 外键字段在多的一方,所以多的一方不能放弃维护关系
    2. 提高关系维护的性能
    <!-- 一对多关系  -->
                <!--
                    inverse:反转控制
                    true:Customer不维护关系
                    false(默认):Customer维护关系
                 -->
                <set name="linkMen" inverse="true">
                    <key column="lkm_cust_id"></key>
                    <one-to-many class="LinkMan"/>
                </set>
    
    1. 如果客户放弃维护与联系人的关系,维护关系的代码可以省略
     @Test
        // 级联保存
        public void testFunc06() {
    
            // 1. 获得session
            Session session = HibernateUtils.openSession();
    
            // 2. 开启事务
            Transaction transaction = session.beginTransaction();
    
            // 3.操作
            // 获得客户
            Customer customer = new Customer();
            customer.setCust_name("baidu");
    
            // 创建联系人
            LinkMan linkMan1 = new LinkMan();
            linkMan1.setLkm_name("maHuaTeng");
    
            LinkMan linkMan2 = new LinkMan();
            linkMan2.setLkm_name("maYunYun");
    
    
            // 建立一对多关系
            // 如果客户放弃维护与联系人的关系,一的一方维护关系的代码可以省略
            // customer.getLinkMen().add(linkMan1);
            // customer.getLinkMen().add(linkMan2);
    
            // 建立多对一关系
            linkMan1.setCustomer(customer);
            linkMan2.setCustomer(customer);
    
            // 保存
            session.save(customer);
    
            session.save(linkMan1);
            session.save(linkMan2);
    
    
            transaction.commit();
            session.close();
        }
    

    4.2 级联操作->删除Customer

    在一对多关系中,有两种删除方案

    1. 设置一的一方也要维护外键关系,这样在删除一的一方表的时候,多的一方的外键会被置为null
    <set name="linkMen" inverse="false">
                    <key column="lkm_cust_id"></key>
                    <one-to-many class="LinkMan"/>
                </set>
    
    1. 直接设置级联关系cascade为级联删除
      这样会把关联的表全部删除,属于危险操作
    <set name="linkMen" cascade="delete">
                    <key column="lkm_cust_id"></key>
                    <one-to-many class="LinkMan"/>
                </set>
    

    5. 多对多关系

    5.1 创建模型

    Snip20180810_39.png

    5.2 创建实体类并书写对应类的配置文件

    1. Role
    public class Role {
    
        private Long role_id;
        private String role_name;
        private String role_memo;
    
        //表达多对多
        private Set<User> users = new HashSet<User>();
    
    
        
    
        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;
        }
    }
    
                <!-- 多对多关系  -->
                <!--
                name: 集合属性名
                table: 配置中间表名
                key 中的  column:外键,别人引用"我"的外键列名
                 class: 我与哪个类是多对多关系
                 column:外键.我引用别人的外键列名
             -->
                <set name="users" table="sys_user_role">
                    <key column="role_id"></key>
                    <many-to-many class="User" column="user_id"/>
                </set>
    
    1. User
    public class User {
    
        private Long user_id;
        private String user_code;
        private String user_name;
        private String user_password;
        private Character user_state;
    
        //表达多对多
        private Set<Role> roles = new HashSet<Role>();
    
    
    
    
    
        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 Character getUser_state() {
            return user_state;
        }
    
        public void setUser_state(Character user_state) {
            this.user_state = user_state;
        }
    
        public Set<Role> getRoles() {
            return roles;
        }
    
        public void setRoles(Set<Role> roles) {
            this.roles = roles;
        }
    }
    
               <!-- 多对多关系  -->
                <!--
                name: 集合属性名
                table: 配置中间表名
                key 中的  column:外键,别人引用"我"的外键列名
                 class: 我与哪个类是多对多关系
                 column:外键.我引用别人的外键列名
             -->
                <set name="roles" table="sys_user_role">
                    <key column="user_id"></key>
                    <many-to-many class="Role" column="role_id"/>
                </set>
    

    6. 多对多操作

    6.1 保存

    1. 配置文件中,让role放弃维护关系
                <!-- 多对多关系  -->
                <!--
                结论: 在开发中,如果遇到多对多关系.一定要选择一方放弃维护关系.
                 一般谁来放弃要看业务方向. 例如录入员工时,需要为员工指定所属角色.
                 那么业务方向就是由员工维护角色. 角色不需要维护与员工关系.角色放弃维护
             -->
                <set name="users" table="sys_user_role" inverse="true">
                    <key column="role_id"></key>
                    <many-to-many class="User" column="user_id"/>
                </set>
    
    1. 测试保存
     // 保存员工以及角色
        @Test
        public void testFunc01() {
    
            Session session = HibernateUtils.openSession();
    
            Transaction transaction = session.beginTransaction();
    
            User user1 = new User();
            user1.setUser_name("zhangSan");
    
            User user2 = new User();
            user2.setUser_name("liSi");
    
    
    
            Role role1 = new Role();
            role1.setRole_name("student");
    
            Role role2 = new Role();
            role2.setRole_name("professor");
    
            // 表达用户多对多关系
            // 因为多对多关系中,是需要在关系表中插入数据,两次插入重复数据的操作会产生错误,所以只能由一方来维护关系,一方放弃维护关系
    
            // user表达关系
            user1.getRoles().add(role1);
            user1.getRoles().add(role2);
    
            user2.getRoles().add(role1);
            user2.getRoles().add(role2);
    
            // role表达关系
            role1.getUsers().add(user1);
            role1.getUsers().add(user2);
    
            role2.getUsers().add(user1);
            role2.getUsers().add(user2);
    
            session.save(user1);
            session.save(user2);
            session.save(role1);
            session.save(role2);
    
            transaction.commit();
    
            session.close();
        }
    

    6.2 为用户新增角色

    // 为员工增加角色
        @Test
        public void testFunc02() {
    
            Session session = HibernateUtils.openSession();
    
            Transaction transaction = session.beginTransaction();
    
            User user = session.get(User.class, 9l);
    
    
            Role role = new Role();
            role.setRole_name("assistant");
    
            // 表达用户多对多关系
    
            // user表达关系
            user.getRoles().add(role);
    
    
            // role表达关系
            role.getUsers().add(user);
    
            session.save(user);
            session.save(role);
    
            transaction.commit();
    
            session.close();
        }
    

    6.3 级联操作和一对多是一样的

    6.4 为用户解除角色

     // 为员工解除角色
        @Test
        public void testFunc03() {
    
            Session session = HibernateUtils.openSession();
    
            Transaction transaction = session.beginTransaction();
    
            User user = session.get(User.class, 9l);
    
    
            Role role = session.get(Role.class, 6l);
    
            // 表达用户多对多关系
    
            // user表达关系
            user.getRoles().remove(role);
    
    
            transaction.commit();
    
            session.close();
        }
    

    7. 为用户保存联系人

    需求


    Snip20180814_40.png

    7.1 创建servlet

    @WebServlet(name = "AddLinkManServlet")
    public class AddLinkManServlet extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        }
    
        private LinkManService linkManService = new LinkManServiceImpl();
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
            LinkMan linkMan = new LinkMan();
    
            try {
                BeanUtils.populate(linkMan, request.getParameterMap());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
    
            // 2.调用service保存客户
            linkManService.save(linkMan);
    
            // 3.重定向到客户列表
            response.sendRedirect(request.getContextPath() + "/ListLinkManServlet");
        }
    }
    

    配置web.xml

    <servlet>
            <description></description>
            <display-name>AddLinkManServlet</display-name>
            <servlet-name>AddLinkManServlet</servlet-name>
            <servlet-class>web.AddLinkManServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>AddLinkManServlet</servlet-name>
            <url-pattern>/AddLinkManServlet</url-pattern>
        </servlet-mapping>
    

    7.2 创建Service和Service的实现类

    public interface LinkManService {
    
        public void save(LinkMan linkMan);
    }
    
    public class LinkManServiceImpl implements LinkManService {
    
    
        private CustomerDao customerDao = new CustomerDaoImpl();
        private LinkManDao linkManDao = new LinkManDaoImpl();
        @Override
        public void save(LinkMan linkMan) {
    
            Session session = HibernateUtils.getCurrentSession();
    
            // 打开事务
            Transaction transaction = session.beginTransaction();
    
            try {
    
                Customer customer = customerDao.getCustomerById(linkMan.getCust_id());
    
                linkMan.setCustomer(customer);
    
    //            customer.getLinkMen().add(linkMan);  ?????
    
                linkManDao.save(linkMan);
    
            } catch (Exception e) {
    
                e.printStackTrace();
    
                transaction.rollback();
            }
    
            transaction.commit();
        }
    }
    

    7.3为CustomerService提供根据id查找Customer的接口和实现方法

     @Override
        public Customer getCustomerById(Long cust_id) {
    
            Session session = HibernateUtils.getCurrentSession();
            return session.get(Customer.class, cust_id);
        }
    

    7.4 创建dao和dao的实现类

    public interface LinkManDao {
        public void save(LinkMan linkMan);
    }
    
    public class LinkManDaoImpl implements LinkManDao {
    
    
        @Override
        public void save(LinkMan linkMan) {
    
            Session session = HibernateUtils.getCurrentSession();
    
            session.save(linkMan);
        }
    }
    

    相关文章

      网友评论

          本文标题:Java mac idea hibernate的使用03

          本文链接:https://www.haomeiwen.com/subject/eglxbftx.html