MyBatis 多表查询之一对多、多对一、多对多

在这里插入图片描述

一、使用 Mybatis 对数据库 User 表一对一查询

第一步:封装对数据库表的映射 User.java

package cn.lemon.domain;

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

public class User implements Serializable {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", birthday=" + birthday +
                ", sex='" + sex + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

第二步:新建持久层(dao)接口 IUserDao.java ,操作数据库

package cn.lemon.dao;

import cn.lemon.domain.User;

import java.util.List;

public interface IUserDao {
    int update(User user);

    User findById(Integer userId);

    List<User> findAll(User user);
}

第三步:新建配置文件 SqlMapConfig.xml 和 jdbc.properties

<?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">
<!--mybatis 配置文件-->
<configuration>
    <!--使用 属性文件 jdbc.properties-->
    <properties resource="jdbc.properties"></properties>
    <!--定义别名-->
    <typeAliases>
        <!--定义单个别名-->
        <!--<typeAlias type="cn.lemon.domain.User" alias="user"></typeAlias>-->
        <!--配置包定义别名-->
        <package name="cn.lemon.domain"></package>
    </typeAliases>

    <!--配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <!--事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置连接池数据源-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"></property>
                <property name="url" value="${jdbc.url}"></property>
                <property name="username" value="${jdbc.user}"></property>
                <property name="password" value="${jdbc.password}"></property>
            </dataSource>
        </environment>
    </environments>
    <!--配置映射文件-->
    <mappers>
        <!--配置包的映射文件-->
        <package name="cn.lemon.dao"></package>
    </mappers>
</configuration>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///db_mybatis?serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=lemon

第四步:编写持久层接口的映射文件 IUserDao.xml (注意文件路径)

<?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.lemon.dao.IUserDao">
    <!--定义Sql片段-->
    <sql id="defaultSql">
        select * from user
    </sql>
    <update id="update" parameterType="user">
        update user
        <set>
            <if test="username != null and username.trim() != ''">
                username = #{username},
            </if>
            <if test="birthday != null">
                birthday = #{birthday},
            </if>
            <if test="sex != null and sex.trim() != ''">
                sex = #{sex},
            </if>
            <if test="address != null and address.trim() != ''">
                address = #{address}
            </if>
        </set>
        where id = #{id};
    </update>
    <select id="findById" parameterType="int" resultType="user">
        /*导入定义Sql片段*/
        <include refid="defaultSql"></include>
        where id = #{id}
    </select>
    <select id="findAll" resultType="user" parameterType="user">
        <include refid="defaultSql"></include>
        <where>
            <if test="username != null and username.trim() !=''">
                and username like '%${username}%'
            </if>
            <if test="birthday != null and birthday.trim() !=''">
                and birthday like '%${birthday}%'
            </if>
            <if test="sex != null and sex.trim() !=''">
                and sex like '%${sex}%'
            </if>
            <if test="address != null and address.trim() !=''">
                and address like '%${address}%'
            </if>
        </where>
    </select>
</mapper>

第五步:拷贝日志文件 log4j.properties,这样我们就可以在控制台看到打印日志

# 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
log4j.rootCategory=debug, CONSOLE

# 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=d:\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

第六步:测试类

package cn.lemon.dao;

import cn.lemon.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;


public class IUserDaoTest {
    private InputStream inputStream;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private IUserDao iUserDao;
    private SimpleDateFormat simpleDateFormat;

    @Before
    public void init() throws Exception {
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");//以流的形式获取配置文件
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//产生mybatis 工厂类
        sqlSession = sqlSessionFactory.openSession(true);//得到session ,true 表示打开自动提交事务
        iUserDao = sqlSession.getMapper(IUserDao.class);//得到mybatis 的mapper代理对象
        simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//String转date
    }

    @After
    public void destroy() throws Exception {
        //关闭资源
        sqlSession.close();
        inputStream.close();
    }

    @Test
    public void update() throws Exception{
        User user = new User();
        user.setId(64);
        user.setUsername("章泽天");
        user.setBirthday(simpleDateFormat.parse("2017-1-12 10:10:10"));
        user.setSex("女");
        user.setAddress("北京");
        iUserDao.update(user);
    }

    @Test
    public void findById() {
        User user = iUserDao.findById(64);
        System.out.println(user);
    }

    @Test
    public void findAll() {
        User user = new User();
        user.setUsername("李");
        user.setSex("男");
        user.setAddress("北京");
        List<User> userList = iUserDao.findAll(user);
        for (User u : userList) {
            System.out.println(u);
        }
    }
}

二、一对多

第一步:新建映射账户表的实体类 Account.java,记得写上记录关联关系的属性

package cn.lemon.domain;

public class Account {
    private Integer id;//主键
    private Integer uid;//外键
    private Double money;

    //关联属性:记录关联关系
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public Double getMoney() {
        return money;
    }

    public void setMoney(Double money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account表——{" +
                "id=" + id +
                ", uid(外键)对应User表中的id=" + uid +
                ", money=" + money +
                '}';
    }
}

第二步:新建持久层接口 IAccountDao.java

package cn.lemon.dao;

import cn.lemon.domain.Account;

import java.util.List;

public interface IAccountDao {
    List<Account> findAll();//查询所有账号
}

第三步:新建映射文件 IAccountDao.xml(配置是重点)

<?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.lemon.dao.IAccountDao">
    <!--配置查询所有-->
    <select id="findAll" resultMap="accountMapLemon">
        <!--使用显式内连接查询(或隐式内连接)-->
        select u.*, a.id as aid, a.uid, a.money from account a inner join user u on a.uid = u.id;
        <!--select u.*, a.id as aid, a.uid, a.money from account a, user u where a.uid = u.id-->
    </select>
    <!--resultMap 处理映射,建立表与表的对应关系-->
    <resultMap id="accountMapLemon" type="account">
        <id property="id" column="aid"/><!--property:属性,column:列名-->
        <result property="uid" column="uid"/>
        <result property="money" column="money"/>
        <!--
            association : 映射从表方
            映射多对一,多的一方的实体属性
        -->
        <association property="user" javaType="user">
            <id property="id" column="id"/><!--主键不能省略-->
            <result property="username" column="username"/>
            <result property="birthday" column="birthday"/>
            <result property="sex" column="sex"/>
            <result property="address" column="address"/>
        </association>
    </resultMap>
</mapper>

在这里插入图片描述
第四步:测试类

package cn.lemon.dao;

import cn.lemon.domain.Account;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

import static org.junit.Assert.*;

public class IAccountDaoTest {
    private InputStream inputStream;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private IAccountDao iAccountDao;

    @Before
    public void init() throws Exception {
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession(true);
        iAccountDao = sqlSession.getMapper(IAccountDao.class);
    }

    @Test
    public void findAll() {
        List<Account> accountList = iAccountDao.findAll();
        for (Account account : accountList) {
            System.out.println(account);
            System.out.println(account.getUser());
            System.out.println("------------------------------");
        }
    }

    @After
    public void destroy() throws Exception {
        //关闭资源
        sqlSession.close();
        inputStream.close();
    }
}

三、多对一

第一步:在实体类 User.java 中添加 Account 属性,并生成 get 和 set 方法

private List<Account> accountList = new ArrayList<>();

第二步:修改映射文件 IUserDao.xml 中的 findAll 方法

   <!--配置查询所有-->
    <select id="findAll2" resultMap="userMapLemon">
        select u.*, a.id as aid, a.uid, a.money from account a inner join user u on a.uid = u.id;
    </select>
    <!--resultMap 处理映射,建立表与表之间的对应关系-->
    <resultMap id="userMapLemon" type="user">
        <id column="id" property="id"/><!--column:列明  property:属性-->
        <result column="username" property="username"/>
        <result column="address" property="address"/>
        <result column="sex" property="sex"/>
        <result column="birthday" property="birthday"/>
        <!--
            collection 是用于建立一对多中集合属性的对应关系
            ofType 用于指定集合元素的数据类型,可以写别名

            collection 部分定义了用户关联的账户信息。表示关联查询结果集,映射一对多中一的一方(也就是主表方)
            property="accList":关联查询的结果集存储在 User 对象的上哪个属性。
            ofType="account":指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也可以使用全限定名。
        -->
        <collection property="accountList" ofType="Account">
            <id column="aid" property="id"/>
            <result column="uid" property="uid"/>
            <result column="money" property="money"/>
        </collection>
    </resultMap>

在这里插入图片描述
第三步:测试类中添加方法

    @Test
    public void findAll2(){
        List<User> userList = iUserDao.findAll2();
        for (User user : userList) {
            System.out.println(user);
            System.out.println(user.getAccountList());
            System.out.println("----------------------------");
        }
    }

四、多对多

user 表与 role 表之间是多对多

查询角色我们需要用到 role 表,但角色分配的用户的信息我们并不能直接找到用户信息,而是要通过中间表( user_role 表)才能关联到用户信息。SQL语句为:(显式内联)

SELECT
	r.*, u.id uid,
	u.username username,
	u.birthday birthday,
	u.sex sex,
	u.address address
FROM 
	role r
INNER JOIN 
	user_role ur
ON ( r.id = ur.rid)
INNER JOIN 
	user u
ON (ur.uid = u.id);

在这里插入图片描述
第一步:新建实体类 Role.java

package cn.lemon.domain;

import java.util.ArrayList;
import java.util.List;

public class Role {
    private Integer roleId;
    private String roleName;
    private String roleDesc;

    private List<User> userList = new ArrayList<>();

    public Integer getRoleId() {
        return roleId;
    }

    public void setRoleId(Integer roleId) {
        this.roleId = roleId;
    }

    public String getRoleName() {
        return roleName;
    }

    public void setRoleName(String roleName) {
        this.roleName = roleName;
    }

    public String getRoleDesc() {
        return roleDesc;
    }

    public void setRoleDesc(String roleDesc) {
        this.roleDesc = roleDesc;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    @Override
    public String toString() {
        return "Role{" +
                "roleId=" + roleId +
                ", roleName='" + roleName + '\'' +
                ", roleDesc='" + roleDesc + '\'' +
                '}';
    }
}

第二步:持久层新建查询所有角色 IRoleDao.java 接口

package cn.lemon.dao;

import cn.lemon.domain.Role;

import java.util.List;

public interface IRoleDao {
    List<Role> findAll();//查询所有角色
}

第三步:映射文件 IRoleDao.xml

<?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.lemon.dao.IRoleDao">
    <select id="findAll" resultMap="roleMapLemon">
        SELECT r.*, u.id uid, u.username username, u.birthday birthday, u.sex sex, u.address address FROM role r INNER JOIN user_role ur ON ( r.id = ur.rid) INNER JOIN user u ON (ur.uid = u.id);
    </select>
    <!--resultMap 处理映射,建立表与表的对应关系-->
    <resultMap id="roleMapLemon" type="role">
        <id property="roleId" column="id"/>
        <result property="roleName" column="role_name"/>
        <result property="roleDesc" column="role_desc"/>
        <!--映射集合-->
        <collection property="userList" ofType="user">
            <id property="id" column="uid"/>
            <result property="username" column="username"/>
            <result property="birthday" column="birthday"/>
            <result property="sex" column="sex"/>
            <result property="address" column="address"/>
        </collection>
    </resultMap>
</mapper>

第四步:测试类

package cn.lemon.dao;

import cn.lemon.domain.Role;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.List;

public class IRoleDaoTest {
    private InputStream inputStream;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession sqlSession;
    private IRoleDao iRoleDao;

    @Before
    public void init() throws Exception {
        inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        sqlSession = sqlSessionFactory.openSession(true);
        iRoleDao = sqlSession.getMapper(IRoleDao.class);
    }

    @Test
    public void findAll() {
        List<Role> roleList = iRoleDao.findAll();
        for (Role role : roleList) {
            System.out.println(role);
            System.out.println(role.getUserList());
            System.out.println("------------------------");
        }
    }

    @After
    public void destroy() throws Exception {
        sqlSession.close();
        inputStream.close();
    }
}

代码下载请 点击

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章