Hibernate (一对多,多对一,多对多)配置

使用技术

  • idea开发工具
  • MySQL数据库
  • hibernate ORM框架

项目整体结构
Hibernate (一对多,多对一,多对多)配置_第1张图片
pom.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.aptech.hdax</groupId>
    <artifactId>TestMysqlHiber</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- hibernate核心-->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.10.Final</version>
        </dependency>
        <!-- MySQL驱动jar-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <!--    Oracle JDBC驱动连接    -->
        <dependency>
            <groupId>oracle</groupId>
            <artifactId>oracle6g</artifactId>
            <version>11.12</version>
        </dependency>
        <!--    junit单元测试    -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <!--        lombok插件、简化getter\setter-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>


</project>

hibernate.cfg.xml 配置文件

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <!--    连接四个串-->
    <property name="connection.url">jdbc:mysql://localhost:3306/ry?serverTimezone=UTC</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <!--显示查询语句-->
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <!--    MySQL方言-->
<!--    <property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>-->
    <property name="dialect">org.hibernate.dialect.MySQL55Dialect</property>

    <!--    引入配置映射文件-->
    <mapping resource="mappers/SysUser.hbm.xml"/>
    <mapping resource="mappers/SysRole.hbm.xml"/>
    <mapping resource="mappers/SysDept.hbm.xml"/>
<!--    <mapping resource="org/aptech/hdax/pojo/Project.hbm.xml"/>-->

  </session-factory>
</hibernate-configuration>

实体类:用户

package org.aptech.hdax.pojo;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;

/**
 * 用户实体类
 */
@Getter
@Setter
public class SysUser implements Serializable {
    private Long userId;
    private SysDept sysDept;//用户所属部门
    private String loginName;
    private String userName;
    private String userType;
    private String email;
    private String phonenumber;
    private String sex;
    private String avatar;
    private String password;
    private String salt;
    private String status;
    private String delFlag;
    private String loginIp;
    private Timestamp loginDate;
    private String createBy;
    private Timestamp createTime;
    private String updateBy;
    private Timestamp updateTime;
    private String remark;
    //用户对应角色、多对多
    private Set<SysRole> sysRoles = new HashSet<SysRole>();//用户所属的角色列表

}

实体类:部门

package org.aptech.hdax.pojo;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Set;

/**
 * 部门实体类
 */
@Getter
@Setter
public class SysDept implements Serializable {
    private Long deptId;
    //private Long parentId;//自引用
    private String ancestors;
    private String deptName;
    private Integer orderNum;
    private String leader;
    private String phone;
    private String email;
    private String status;
    private String delFlag;
    private String createBy;
    private Date createTime;
    private String updateBy;
    private Date updateTime;

    private SysDept parent;//父级部门

    //一对多
    private Set<SysDept> children;//子级部门集合(自引用)

}

实体类:角色

package org.aptech.hdax.pojo;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.Date;
import java.util.Set;

/**
 * 角色实体类
 */
@Getter
@Setter
public class SysRole implements Serializable {
    private Long roleId;
    private String roleName;
    private String roleKey;
    private Integer roleSort;
    private String dataScope;
    private String status;
    private String delFlag;
    private String createBy;
    private Date createTime;
    private String updateBy;
    private Date updateTime;
    private String remark;
    //角色对应的用户集合,多对多
    private Set<SysUser> sysUsers;

}

映射文件:SysUser.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="org.aptech.hdax.pojo.SysUser" table="sys_user" schema="ry">
        <!--  用户id主键自增、手动赋值-->
        <id name="userId" column="user_id">
            <generator class="native"></generator>
        </id>
        <property name="loginName" column="login_name"/>
        <property name="userName" column="user_name"/>
        <property name="userType" column="user_type"/>
        <property name="email" column="email"/>
        <property name="phonenumber" column="phonenumber"/>
        <property name="sex" column="sex"/>
        <property name="avatar" column="avatar"/>
        <property name="password" column="password"/>
        <property name="salt" column="salt"/>
        <property name="status" column="status"/>
        <property name="delFlag" column="del_flag"/>
        <property name="loginIp" column="login_ip"/>
        <property name="loginDate" column="login_date"/>
        <property name="createBy" column="create_by"/>
        <property name="createTime" column="create_time"/>
        <property name="updateBy" column="update_by"/>
        <property name="updateTime" column="update_time"/>
        <property name="remark" column="remark"/>
        <!-- 多对一 默认是延迟加载查询出是两条语句、可以用一条语句连表语句查询-->
        <many-to-one name="sysDept" class="org.aptech.hdax.pojo.SysDept" column="dept_id" fetch="join"/>

        <!-- 多对多、配置\ 多对多需要有关系表-->
        <set name="sysRoles" table="sys_user_role">
        <!--key用户表的外键-->
            <key column="user_id"></key>
            <!-- 用户谁和谁是多对多? 用户和角色是多对多-->
            <many-to-many class="org.aptech.hdax.pojo.SysRole" column="role_id"/>
        </set>
    </class>
</hibernate-mapping>

映射文件:SysDept.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="org.aptech.hdax.pojo.SysDept" table="sys_dept" schema="ry">
        <id name="deptId" column="dept_id"/>
        <!--<property name="parentId" column="parent_id"/>-->
        <property name="ancestors" column="ancestors"/>
        <property name="deptName" column="dept_name"/>
        <property name="orderNum" column="order_num"/>
        <property name="leader" column="leader"/>
        <property name="phone" column="phone"/>
        <property name="email" column="email"/>
        <property name="status" column="status"/>
        <property name="delFlag" column="del_flag"/>
        <property name="createBy" column="create_by"/>
        <property name="createTime" column="create_time"/>
        <property name="updateBy" column="update_by"/>
        <property name="updateTime" column="update_time"/>

        <!--多对一-->
        <many-to-one name="parent" class="org.aptech.hdax.pojo.SysDept" column="parent_id"/>

        <!-- 一对多映射-->
        <set name="children" inverse="true">
            <key column="parent_id"></key>
            <one-to-many class="org.aptech.hdax.pojo.SysDept"/>
        </set>
    </class>
</hibernate-mapping>

映射文件:SysRole.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="org.aptech.hdax.pojo.SysRole" table="sys_role" schema="ry">
        <!--角色id主键自增、手动自增-->
        <id name="roleId" column="role_id">
            <generator class="native"></generator>
        </id>
        <property name="roleName" column="role_name"/>
        <property name="roleKey" column="role_key"/>
        <property name="roleSort" column="role_sort"/>
        <property name="dataScope" column="data_scope"/>
        <property name="status" column="status"/>
        <property name="delFlag" column="del_flag"/>
        <property name="createBy" column="create_by"/>
        <property name="createTime" column="create_time"/>
        <property name="updateBy" column="update_by"/>
        <property name="updateTime" column="update_time"/>
        <property name="remark" column="remark"/>

        <!-- 多对多、配置\ 多对多需要有关系表-->
        <set name="sysUsers" table="sys_user_role" inverse="true">
            <!--key角色表的外键-->
            <key column="role_id"></key>
            <!-- 角色谁和谁是多对多? 角色和用户是多对多-->
            <many-to-many class="org.aptech.hdax.pojo.SysUser" column="user_id"/>
        </set>
    </class>
</hibernate-mapping>

Test 测试类

package org.aptech.hdax.test;

import org.aptech.hdax.pojo.SysDept;
import org.aptech.hdax.pojo.SysRole;
import org.aptech.hdax.pojo.SysUser;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;

public class TestHiber {

    //查询用户所属拥有哪些角色
    @Test
    public void testuserby(){
        //1、读取配置文件
        Configuration config = new Configuration().configure();
        //2、构建session工厂
        SessionFactory sessionFactory = config.buildSessionFactory();
        //3、打开session
        Session session = sessionFactory.openSession();
        //4、操作事物
        Transaction tx = session.beginTransaction();

        SysUser sysUser = session.get(SysUser.class,1L);
        System.out.println(sysUser.getUserName());
        //循环用户下有哪些角色
        for (SysRole sysRole : sysUser.getSysRoles()) {
            System.out.println(sysRole.getRoleName());
        }

        //5、提交事务
        tx.commit();
        //关闭session
        session.close();

    }

    //查询角色拥有哪些用户
    @Test
    public void testroleby(){
        //1、读取配置文件
        Configuration config = new Configuration().configure();
        //2、构建session工厂
        SessionFactory sessionFactory = config.buildSessionFactory();
        //3、打开session
        Session session = sessionFactory.openSession();
        //4、操作事物
        Transaction tx = session.beginTransaction();

        SysRole sysRole = session.get(SysRole.class,1L);
        System.out.println(sysRole.getRoleName());
        //循环角色拥有哪些用户
        for (SysUser sysUser:sysRole.getSysUsers()) {
            System.out.println(sysUser.getUserName());
        }

        //5、提交事务
        tx.commit();
        //关闭session
        session.close();

    }

    //查询用户拥有哪些部门
    @Test
    public void testdeptby(){
        //1、读取配置文件
        Configuration config = new Configuration().configure();
        //2、构建session工厂
        SessionFactory sessionFactory = config.buildSessionFactory();
        //3、打开session
        Session session = sessionFactory.openSession();
        //4、操作事物
        Transaction tx = session.beginTransaction();

        //输出用户名称,所在部门名称
        SysUser sysUser = session.get(SysUser.class,1L);
        System.out.println(sysUser.getUserName());
        System.out.println(sysUser.getSysDept().getDeptName());

        //5、提交事务
        tx.commit();
        //关闭session
        session.close();

    }

    //查询部门拥有哪些子级部门
    @Test
    public void testdeptparentby(){
        //1、读取配置文件
        Configuration config = new Configuration().configure();
        //2、构建session工厂
        SessionFactory sessionFactory = config.buildSessionFactory();
        //3、打开session
        Session session = sessionFactory.openSession();
        //4、操作事物
        Transaction tx = session.beginTransaction();

        //输出部门名称
        SysDept sysDept = session.get(SysDept.class,101L);
        System.out.println(sysDept.getDeptName());
        //输出父级名称
        System.out.println(sysDept.getParent().getDeptName());

        //循环输出子级部门
        for (SysDept child:sysDept.getChildren()) {
            System.out.println(child.getDeptName());
        }

        //5、提交事务
        tx.commit();
        //关闭session
        session.close();

    }


    //查询部门拥有哪些子级部门
    @Test
    public void testdeptuseradd(){
        //1、读取配置文件
        Configuration config = new Configuration().configure();
        //2、构建session工厂
        SessionFactory sessionFactory = config.buildSessionFactory();
        //3、打开session
        Session session = sessionFactory.openSession();
        //4、操作事物
        Transaction tx = session.beginTransaction();

        //查询部门
        SysDept sysDept = session.get(SysDept.class,101L);
        //创建一个角色
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(1L);
        //添加user
        SysUser sysUser = new SysUser();
        sysUser.setSysDept(sysDept);//查询出101的部门
        sysUser.getSysRoles().add(sysRole);//角色为1的
        sysUser.setLoginName("诶皮太壳");
        sysUser.setUserName("邯郸翱翔");

        session.save(sysUser);


        //循环输出子级部门
        for (SysDept child:sysDept.getChildren()) {
            System.out.println(child.getDeptName());
        }

        //5、提交事务
        tx.commit();
        //关闭session
        session.close();

    }

}

你可能感兴趣的:(java)