Hibernate进阶:实体之间的关系表达与操作

一对多

假如存在客户表cst_customer,联系人表cst_linkman。
一个客户对应多个联系人,一个联系人只对应一个客户。

表结构

客户表:cst_customer

主键 字段名 类型
key cust_id BIGINT(32)
cust_name VARCHAR(32)
cust_source VARCHAR(32)
cust_industry VARCHAR(32)
cust_level VARCHAR(32)
cust_linkman VARCHAR(64)
cust_phone VARCHAR(64)
cust_mobile VARCHAR(16)
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_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;

联系人表:cst_linkman

主键 字段名 类型
key lkm_id bigint(32)
lkm_name varchar(16)
lkm_cust_id bigint(32)
lkm_gender char(1)
lkm_phone varchar(16)
lkm_mobile varchar(16)
lkm_email varchar(64)
lkm_qq varchar(16)
lkm_position varchar(16)
lkm_memo varchar(512)
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 `cst_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

实体类

Customer.java

package cn.itcast.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_linkman;
    private String cust_phone;
    private String cust_mobile;
    //使用set集合,表达一对多关系
    private Set<LinkMan> linkMens = new HashSet<LinkMan>();

    public Set<LinkMan> getLinkMens() {
        return linkMens;
    }
    public void setLinkMens(Set<LinkMan> linkMens) {
        this.linkMens = linkMens;
    }
    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 + "]";
    }
}

LinkMan.java

package cn.itcast.domain;
//联系人实体
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 Customer getCustomer() {
        return customer;
    }
    public void setCustomer(Customer customer) {
        this.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;
    }
}

ORM映射配置文件

Customer.hmb.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="cn.itcast.domain" >
    <class name="Customer" table="cst_customer" >
        <id name="cust_id"  >
            <generator class="native"></generator>
        </id>
        <property name="cust_name" column="cust_name" ></property>
        <property name="cust_source" column="cust_source" ></property>
        <property name="cust_industry" column="cust_industry" ></property>
        <property name="cust_level" column="cust_level" ></property>
        <property name="cust_linkman" column="cust_linkman" ></property>
        <property name="cust_phone" column="cust_phone" ></property>
        <property name="cust_mobile" column="cust_mobile" ></property>

        <!-- 集合,一对多关系,在配置文件中配置 -->
        <!-- 
            name属性:集合属性名
            column属性: 外键列名
            class属性: 与我关联的对象完整类名
         -->
         <!-- 
            级联操作:   cascade
                save-update: 级联保存更新
                delete:级联删除
                all:save-update+delete
            级联操作: 简化操作.目的就是为了少些两行代码.
          -->
          <!-- inverse属性: 配置关系是否维护.
                true: customer不维护关系
                false(默认值): customer维护关系

            inverse属性: 性能优化.提高关系维护的性能.
            原则: 无论怎么放弃,总有一方必须要维护关系.
            一对多关系中: 一的一方放弃.也只能一的一方放弃.多的一方不能放弃.
          -->
        <set name="linkMens" inverse="true" cascade="all"  >
            <key column="lkm_cust_id" ></key>
            <one-to-many class="LinkMan" />
        </set>


    </class>
</hibernate-mapping>

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 package="cn.itcast.domain" >
    <class name="LinkMan" table="cst_linkman" >
        <id name="lkm_id"  >
            <generator class="native"></generator>
        </id>
        <property name="lkm_gender"  ></property>
        <property name="lkm_name"  ></property>
        <property name="lkm_phone"  ></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属性: 与我关联的对象完整类名
         -->
          <!-- 
            级联操作:   cascade
                save-update: 级联保存更新
                delete:级联删除
                all:save-update+delete
            级联操作: 简化操作.目的就是为了少些两行代码.
          -->
          <!-- 多的一方: 不能放弃维护关系的.外键字段就在多的一方.  -->
        <many-to-one name="customer" column="lkm_cust_id" class="Customer" cascade="save-update">
        </many-to-one>
    </class>
</hibernate-mapping>

关系操作

package cn.itcast.a_one2many;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.domain.Customer;
import cn.itcast.domain.LinkMan;
import cn.itcast.utils.HibernateUtils;

//测试级联操作
public class Demo2 {
    @Test
    //保存客户 以及客户 下的联系人
    //cascade:save-update
    public void fun1(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        Customer c = new Customer();
        c.setCust_name("传智播客");

        LinkMan lm1 = new LinkMan();
        lm1.setLkm_name("黎活明");

        LinkMan lm2 = new LinkMan();
        lm2.setLkm_name("刘悦东");

        //表达一对多,客户下有多个联系人
        c.getLinkMens().add(lm1);
        c.getLinkMens().add(lm2);

        //表达多对一,联系人属于哪个客户
        lm1.setCustomer(c);
        lm2.setCustomer(c);


        session.save(c);

        //Customer设置了级联添加,下面两条语句可不写。
        //session.save(lm1);
        //session.save(lm2);

        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

    @Test
    //测试删除客户时,级联删除客户下的联系人
    //cascade:delete
    public void fun2(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 获得要操作的客户对象
        Customer c = session.get(Customer.class,1l);
        //2>调用delete删除客户
        //c若设置了级联删除,将同时级联删除c的所有linkman
        session.delete(c);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

    @Test
    //保存联系人以及联系人对应的客户
    //cascade:save-update
    public void fun3(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        Customer c = new Customer();
        c.setCust_name("北大青鸟");

        LinkMan lm1 = new LinkMan();
        lm1.setLkm_name("刘总");

        //表达一对多,客户下有多个联系人
        c.getLinkMens().add(lm1);

        //表达多对一,联系人属于哪个客户
        lm1.setCustomer(c);
        //若lm1设置级联添加,将同时保存c
        session.save(lm1);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }
}

多对多

假如存在员工表sys_user,角色表sys_role
一个员工可以对应多种角色,一种角色可以有多个员工。

表结构

客户表:sys_user

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

联系人表:sys_role

主键 字段名 类型
key role_id bigint(32)
role_name varchar(32)
role_memo varchar(128)
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=6 DEFAULT CHARSET=utf8;

员工角色表:sys_user_role

主键 字段名 类型
user_id bigint(32)
role_id bigint(32)
CREATE TABLE `sys_role` (
  `user_id` bigint(32) NOT NULL,
  `role_id` bigint(32) NOT NULL,
  FOREIGN KEY (user_id) REFERENCES sys_user(user_id),
  FOREIGN KEY (role_id) REFERENCES sys_role(role_id)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

实体类

User.java

package cn.itcast.domain;

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

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;
    }
}

Role.java

package cn.itcast.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<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;
    }
}

ORM映射配置文件

User.hmb.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="cn.itcast.domain" >
    <class name="User" table="sys_user" >
        <id name="user_id"  >
            <generator class="native"></generator>
        </id>
        <property name="user_code"></property>
        <property name="user_name"></property>
        <property name="user_password"></property>
        <property name="user_state" ></property>

        <!-- 多对多关系表达 -->
        <!-- 
            name: 集合属性名
            table: 配置中间表名
            key
             |-column:外键,别人引用"我"的外键列名
             class: 我与哪个类是多对多关系
             column:外键.我引用比人的外键列名
         -->
         <!-- cascade级联操作:
                    save-update: 级联保存更新
                    delete:级联删除
                    all:级联保存更新+级联删除
            结论: cascade简化代码书写.该属性使不使用无所谓. 建议要用只用save-update.
                 如果使用delete操作太过危险.尤其在多对多中.不建议使用.
                     -->
        <set name="roles" table="sys_user_role" cascade="save-update" >
            <key column="user_id"></key>
            <many-to-many class="Role" column="role_id" ></many-to-many>
        </set>

    </class>
</hibernate-mapping>

Role.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="cn.itcast.domain" >
    <class name="Role" table="sys_role" >
        <id name="role_id"  >
            <generator class="native"></generator>
        </id>
        <property name="role_name"  ></property>
        <property name="role_memo"  ></property>

    <!-- 使用inverse属性
            true: 放弃维护外键关系
            false(默认值):维护关系

        结论: 将来在开发中,如果遇到多对多关系.一定要选择一方放弃维护关系.
             一般谁来放弃要看业务方向. 例如录入员工时,需要为员工指定所属角色.
             那么业务方向就是由员工维护角色. 角色不需要维护与员工关系.角色放弃维护
         -->
        <set name="users" table="sys_user_role" inverse="true" >
            <key column="role_id" ></key>
            <many-to-many class="User" column="user_id" ></many-to-many>
        </set>
    </class>
</hibernate-mapping>

关系操作

package cn.itcast.b_many2many;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import cn.itcast.domain.Role;
import cn.itcast.domain.User;
import cn.itcast.utils.HibernateUtils;

//多对多关系操作
public class Demo {
    @Test
    //保存员工以及角色
    public void fun1(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 创建两个 User
        User u1 = new User();
        u1.setUser_name("郝强勇");

        User u2 = new User();
        u2.setUser_name("金家德");

        //2> 创建两个 Role
        Role r1 = new Role();
        r1.setRole_name("保洁");

        Role r2 = new Role();
        r2.setRole_name("保安");
        //3> 用户表达关系
        u1.getRoles().add(r1);
        u1.getRoles().add(r2);

        u2.getRoles().add(r1);
        u2.getRoles().add(r2);

        //4> 角色表达关系
        r1.getUsers().add(u1);
        r1.getUsers().add(u2);

        r2.getUsers().add(u1);
        r2.getUsers().add(u2);

        //5> 调用Save方法一次保存
        session.save(u1);
        session.save(u2);
        session.save(r1);
        session.save(r2);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }


    @Test
    //为郝强勇新增一个角色
    public void fun3(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 获得郝强勇用户
        User user = session.get(User.class, 1l);
        //2> 创建公关角色
        Role r = new Role();
        r.setRole_name("男公关");
        //3> 将角色添加到用户中
        user.getRoles().add(r);
        //4> 将角色转换为持久化
        //session.save(r);
        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }

    @Test
    //为郝强勇解除一个角色
    public void fun4(){
        //1 获得session
        Session session = HibernateUtils.openSession();
        //2 开启事务
        Transaction tx = session.beginTransaction();
        //-------------------------------------------------
        //3操作
        //1> 获得郝强勇用户
        User user = session.get(User.class, 1l);
        //2> 获得要操作的角色对象(保洁,保安)
        Role r1 = session.get(Role.class, 1l);
        Role r2 = session.get(Role.class, 2l);
        //3> 将角色从用户的角色集合中移除
        user.getRoles().remove(r1);
        user.getRoles().remove(r2);

        //-------------------------------------------------
        //4提交事务
        tx.commit();
        //5关闭资源
        session.close();
    }
}
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇