对应关系

一个用户(user)可以拥有多个角色(role),一个角色可以被多个用户拥有,即user与role为多对多关系。

数据库设计

user表

role表

user_role关系表

多表查询SQL语句

select
u.id as uid,
u.username as uname,
u.birthday as birthday,
u.sex as sex,
u.address as address,
r.ID as rid,
r.ROLE_NAME as rname,
r.ROLE_DESC as rdesc
from user as u
left outer join user_role ur on ur.UID=u.id
left outer join role r on r.ID=ur.RID

数据实体

封装用户数据

public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
    //一个用户,可以用多个角色,同时,一个角色被多个用户同时拥有,多对多关系映射
    List<Role> roles;
    //省去getter、setter以及toString
}

封装角色实体

public class Role {
    private int ID;
    private String ROLE_NAME;
    private String ROLE_DESC;
    //省去getter、setter以及toString
}

查询接口

public interface IUserDao {
    List<User> getUsersWithRole();
}

添加依赖

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.12</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.11</version>
</dependency>

配置文件

log4j.properties

此文件放在 src/main/resources 目录下。

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=debug, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=e:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

主配置文件SqlMapCfg.xml

此文件放在 src/main/resources 目录下。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias type="cn.henuajy.bean.User" alias="user"/>
        <typeAlias type="cn.henuajy.bean.Role" alias="role"/>
    </typeAliases>
    <environments default="mysql">
        <environment id="mysql">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${name}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 映射配置文件 -->
    <mappers>
        <mapper resource="cn\henuajy\dao\IUserDao.xml"/>
    </mappers>
</configuration>

映射配置文件IUserDao.xml

此放在 src/main/resources/cn/henuajy/dao 目录下。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.henuajy.dao.IUserDao">
    <resultMap id="getUsersWithRole" type="user">
        <id property="id" column="uid"/>
        <result property="username" column="uname"/>
        <result property="birthday" column="birthday"/>
        <result property="sex" column="sex"/>
        <result property="address" column="address"/>
        <collection property="roles" ofType="role">
            <id property="ID" column="rid"/>
            <result property="ROLE_NAME" column="rname"/>
            <result property="ROLE_DESC" column="rdesc"/>
        </collection>
    </resultMap>
    <select id="getUsersWithRole" resultMap="getUsersWithRole">
        select
        u.id as uid,
        u.username as uname,
        u.birthday as birthday,
        u.sex as sex,
        u.address as address,
        r.ID as rid,
        r.ROLE_NAME as rname,
        r.ROLE_DESC as rdesc
        from user as u
        left outer join user_role ur on ur.UID=u.id
        left outer join role r on r.ID=ur.RID
    </select>
</mapper>

进行查询

public void test() throws IOException {
    InputStream in = Resources.getResourceAsStream("SqlMapCfg.xml");
    SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    SqlSessionFactory factory = builder.build(in);
    SqlSession session = factory.openSession();
    IUserDao userDao = session.getMapper(IUserDao.class);
    List<User> users = userDao.getUsersWithRole();

    for (User user:users) System.out.println(user.toString());

    session.close();
    in.close();
}

版权声明:本文为HenuAJY原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/HenuAJY/p/13208345.html