1. Mybatis 多表查询
本次案例主要以最为简单的用户和账户的模型来分析
Mybatis
多表关系。用户为User
表,账户为Account
表。一个用户(User
)可以有多个账户(Account
)。具体关系如下:
1.1 Mybatis 多表查询之一对一(多对一)
1.1.1 方式一
需求:查询所有账户信息,关联查询下单用户信息。
注意:因为一个账户信息只能供某个用户使用,所以从查询账户信息出发关联查询用户信息为一对一查询。如果从用户信息出发查询用户下的账户信息则为一对多查询,因为一个用户可以有多个账户。
(1)创建数据库并编写账户信息的实体类
CREATE TABLE `user` (
`id` int NOT NULL AUTO_INCREMENT,
`username` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名称',
`birthday` datetime NULL DEFAULT NULL COMMENT '生日',
`sex` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '性别',
`address` varchar(256) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '地址',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 61 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
CREATE TABLE `account` (
`ID` int NOT NULL COMMENT '编号',
`UID` int NULL DEFAULT NULL COMMENT '用户编号',
`MONEY` double NULL DEFAULT NULL COMMENT '金额',
PRIMARY KEY (`ID`) USING BTREE,
INDEX `FK_Reference_8`(`UID`) USING BTREE,
CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ON DELETE RESTRICT ON UPDATE RESTRICT
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
package com.spg.entity;
public class Account {
private Integer id;
private String uid;
private Double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUid() {
return uid;
}
public void setUid(String 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='" + uid + '\'' +
", money=" + money +
'}';
}
}
(2)编写 sql 语句
实现查询账户信息时,也要查询账户所对应的用户信息。
select a.*, u.username, u.address
from account a, user u
where a.UID = u.id
在 MySQL 中测试的查询结果如下:
(3)定义 AccountUser 类
为了能够封装上面 SQL 语句的查询结果,定义
AccountCustomer
类中要包含账户信息同时还要包含用户信息,所以我们要在定义AccountUser
类时可以继承 User 类。
package com.spg.entity;
public class AccountUser extends Account{
private String username;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return super.toString() + " AccountUser{" +
"username='" + username + '\'' +
", address='" + address + '\'' +
'}';
}
}
(4)账户的持久层 Dao 接口加入查询方法
package com.spg.dao;
import com.spg.entity.AccountUser;
import java.util.List;
/**
* 账户的持久层接口
*/
public interface AccountDao {
/**
* 查询所有账户,同时获取账户的所属用户名称以及它的地址信息
* @return
*/
List<AccountUser> findAll();
}
(5)账户的持久层 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="com.spg.dao.AccountDao">
<!-- 配置查询所有操作-->
<select id="findAll" resultType="com.spg.entity.AccountUser">
select a.*, u.username, u.address
from account a, user u
where a.UID = u.id
</select>
</mapper>
注意:因为上面查询的结果中包含了账户信息同时还包含了用户信息,所以我们的返回值类型
returnType
的值设置为AccountUser
类型,这样就可以接收账户信息和用户信息了。
(6)编写mybatis的配置文件mybatis-config.xml
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_db?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
<?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>
<!-- 配置连接数据库的信息 -->
<!--<properties url="file:///E:/Users/IdeaProjects/mybatis_idea/mybatis_day02_curd/src/main/resources/jdbcConfig.properties"/>
--><properties resource="jdbcConfig.properties"/>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境-->
<environment id="mysql">
<!-- 配置事务的类型-->
<transactionManager type="JDBC"/>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<mapper resource="mapper/AccountDao.xml"/>
</mappers>
</configuration>
(7)创建 AccountDaoTest 测试类
package com.spg.dao;
import com.spg.entity.AccountUser;
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 AccountDaoTest {
private InputStream in ;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private AccountDao accountDao;
@Before//在测试方法执行之前执行
public void init() throws Exception {
//1.读取配置文件
in = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3.创建 SqlSession 工厂对象
factory = builder.build(in);
//4.创建 SqlSession 对象
sqlSession = factory.openSession();
//5.创建 Dao 的代理对象
accountDao = sqlSession.getMapper(AccountDao.class);
}
@After//在测试方法执行完成之后执行
public void destroy() throws Exception {
sqlSession.commit();
//7.释放资源
sqlSession.close();
in.close();
}
@Test
public void findAll() {
//6.执行操作
List<AccountUser> accountUserList = accountDao.findAll();
for(AccountUser accountUser : accountUserList) {
System.out.println(accountUser);
}
}
}
测试结果:
1.1.2 方式二
使用
resultMap
,定义专门的resultMap
用于映射一对一查询结果。
通过面向对象的(has a)
关系可以得知,我们可以在Account
类中加入一个User
类的对象来代表这个账户是哪个用户的。
(1)修改 Account 实体类
package com.spg.entity;
import java.util.Date;
public class User {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
package com.spg.entity;
public class Account {
private Integer id;
private String 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 String getUid() {
return uid;
}
public void setUid(String 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='" + uid + '\'' +
", money=" + money +
'}';
}
}
(2)修改 AccountDao 接口中的方法
/**
* 查询所有账户,同时获取账户的所属用户名称以及它的地址信息
* @return
*/
List<Account> findAll();
注意:第二种方式,将返回值改 为了
Account
类型。因为Account
类中包含了一个User
类的对象,它可以封装账户所对应的用户信息。
(3)重新定义 AccountDao.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="com.spg.dao.AccountDao">
<!-- 定义封装account和user的resultMap 建立对应关系 -->
<resultMap type="com.spg.entity.Account" id="accountMap">
<id column="aid" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
<!-- 配置user对象中accounts集合的映射 -->
<!-- 它是用于指定从表方的引用实体属性的 -->
<association property="user" javaType="com.spg.entity.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<result column="address" property="address"/>
</association>
</resultMap>
<select id="findAll" resultMap="accountMap">
select u.*, a.id as aid, a.uid, a.money
from account a, user u
where a.uid =u.id;
</select>
</mapper>
(4)在 AccountDaoTest 类中加入测试方法
@Test
public void findAll() {
List<Account> accountList = accountDao.findAll();
for(Account account : accountList) {
System.out.println(account);
System.out.println(account.getUser());
}
}
测试结果:
1.3 Mybatis 多表查询之一对多
需求:查询所有用户信息及用户关联的账户信息。
分析:用户信息和他的账户信息为一对多关系,并且查询过程中如果用户没有账户信息,此时也要将用户信息查询出来,我们想到了左外连接查询比较合适。
1.3.1 编写 SQL 语句
select u.*,a.id as aid ,a.uid,a.money
from user u
left outer join account a
on u.id = a.UID
测试该 SQL 语句在 MySQL 客户端工具的查询结果如下:
1.3.2 User 类加入 List<Account>
//一对多关系映射:主表实体应该包含从表实体的集合引用
private List<Account> accounts;
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
1.3.3 用户持久层 Dao 接口中加入查询方法
package com.spg.dao;
import com.spg.entity.User;
import java.util.List;
public interface UserDao {
/**
* 查询所有用户,同时获取出每个用户下的所有账户信息
* @return
*/
List<User> findAll();
}
1.3.4 用户持久层 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="com.spg.dao.UserDao">
<!-- 定义User的resultMap-->
<resultMap type="com.spg.entity.User" id="userMap">
<id column="id" property="id"></id>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
<!-- collection 是用于建立一对多中集合属性的对应关系
ofType 用于指定集合元素的数据类型
-->
<collection property="accounts" ofType="com.spg.entity.Account">
<id column="aid" property="id"/>
<result column="uid" property="uid"/>
<result column="money" property="money"/>
</collection>
</resultMap>
<!-- 配置查询所有操作 -->
<select id="findAll" resultMap="userMap">
select u.*,a.id as aid ,a.uid,a.money
from user u
left outer join account a
on u.id = a.UID
</select>
</mapper>
collection
:部分定义了用户关联的账户信息。表示关联查询结果集
-property="accList"
: 关联查询的结果集存储在 User 对象的上哪个属性。
-ofType="account"
:指定关联查询的结果集中的对象类型即List中的对象类型。此处可以使用别名,也可以使用全限定名。
1.3.5 在 AccountDaoTest 类中加入测试方法
package com.spg.dao;
import com.spg.entity.AccountUser;
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 AccountDaoTest {
private InputStream in ;
private SqlSessionFactory factory;
private SqlSession sqlSession;
private UserDao userDao;
@Before//在测试方法执行之前执行
public void init() throws Exception {
//1.读取配置文件
in = Resources.getResourceAsStream("mybatis-config.xml");
//2.创建构建者对象
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
//3.创建 SqlSession 工厂对象
factory = builder.build(in);
//4.创建 SqlSession 对象
sqlSession = factory.openSession();
//5.创建 Dao 的代理对象
userDao= sqlSession.getMapper(UserDao.class);
}
@After//在测试方法执行完成之后执行
public void destroy() throws Exception {
sqlSession.commit();
//7.释放资源
sqlSession.close();
in.close();
}
@Test
public void testFindAll() {
//6.执行操作
List<User> userList = userDao.findAll();
for(User user : userList) {
System.out.println("每个用户的内容:");
System.out.println(user);
System.out.println(user.getAccounts());
}
}
}
测试结果:
1.4 Mybatis 多表查询之多对多
多对多关系其实我们看成是双向的一对多关系。
1.4.1 实现 Role 到 User 多对多
(1)用户与角色的关系模型
用户与角色的多对多关系模型如下:
在 MySQL 数据库中添加角色表,用户角色的中间表。
用户表:
角色表:
用户角色中间表:
(2)业务要求及实现 SQL
需求: 实现查询所有对象并且加载它所分配的用户信息。
分析: 查询角色我们需要用到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)
(3)角色实体类
package com.spg.entity;
import java.util.Date;
public class User {
private Integer id;
private String username;
private String address;
private String sex;
private Date birthday;
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", address='" + address + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
'}';
}
}
package com.spg.entity;
import java.util.List;
public class Role {
private Integer roleId;
private String roleName;
private String roleDesc;
//多对多的关系映射:一个角色可以赋予多个用户
private List<User> users;
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
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;
}
@Override
public String toString() {
return "Role{" +
"roleId=" + roleId +
", roleName='" + roleName + '\'' +
", roleDesc='" + roleDesc + '\'' +
'}';
}
}
(4)Role持久层Dao接口加入查询方法
package com.spg.dao;
import com.spg.entity.Role;
import java.util.List;
public interface RoleDao {
/**
* 查询所有角色
* @return
*/
List<Role> findAll();
}
(5)Role持久层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="com.spg.dao.RoleDao">
<!--定义 role 表的 ResultMap-->
<resultMap id="roleMap" type="Role">
<id property="roleId" column="rid"/>
<result property="roleName" column="role_name"/>
<result property="roleDesc" column="role_desc"/>
<collection property="users" ofType="User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="address" property="address"/>
<result column="sex" property="sex"/>
<result column="birthday" property="birthday"/>
</collection>
</resultMap>
<!--查询所有-->
<select id="findAll" resultMap="roleMap">
select u.*,r.id as rid,r.role_name,r.role_desc from role r
left outer join user_role ur on r.id = ur.rid
left outer join user u on u.id = ur.uid
</select>
</mapper>
(6)mybatis-config.xml配置
# 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=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
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_db?serverTimezone=UTC
jdbc.username=root
jdbc.password=root
<?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>
<!-- 配置properties-->
<properties resource="jdbcConfig.properties"/>
<!--使用typeAliases配置别名,它只能配置entity中类的别名 -->
<typeAliases>
<!--<package name="com.spg.entity"/> -->
<typeAlias type="com.spg.entity.User" alias="User"/>
<typeAlias type="com.spg.entity.Role" alias="Role"/>
</typeAliases>
<!-- 配置环境 -->
<environments default="mysql">
<!-- 配置mysql的环境-->
<environment id="mysql">
<!-- 配置事务的类型-->
<transactionManager type="JDBC"/>
<!-- 配置数据源(连接池) -->
<dataSource type="POOLED">
<!-- 配置连接数据库的4个基本信息 -->
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<!-- 指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
<mappers>
<!--<package name="com.spg.dao"/>-->
<mapper resource="mapper/RoleDao.xml"/>
</mappers>
</configuration>
(7)在RoleDaoTest类中加入测试方法
package com.spg.dao;
import com.spg.entity.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;
import static org.junit.Assert.*;
public class RoleDaoTest {
private InputStream in;
private SqlSession sqlSession;
private RoleDao roleDao;
@Before//用于在测试方法执行之前执行
public void init() throws Exception {
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("mybatis-config.xml");
//2.获取 SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取 SqlSession 对象
sqlSession = factory.openSession(true);
//4.获取 dao 的代理对象
roleDao = sqlSession.getMapper(RoleDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy() throws Exception {
//提交事务
// sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void findAll() {
List<Role> roleList = roleDao.findAll();
for(Role role : roleList){
System.out.println("每个角色的信息:");
System.out.println(role);
System.out.println(role.getUsers());
}
}
}
测试结果:
1.4.2 实现 User 到 Role 的多对多
从 User
出发,我们也可以发现一个用户可以具有多个角色,这样用户到角色的关系也还是一对多关系。这样我们就可以认为 User
与 Role
的多对多关系,可以被拆解成两个一对多关系来实现。
(1)用户实体类加入List<Role>
//多对多的关系映射:一个用户可以具备多个角色
private List<Role> roles;
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
(2)用户持久层Dao接口加入查询方法
package com.spg.dao;
import com.spg.entity.User;
import java.util.List;
public interface UserDao {
/**
* 查询所有用户,同时获取到用户下所有账户的信息
* @return
*/
List<User> findAll();
}
(3)用户持久层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="com.spg.dao.UserDao">
<!-- 定义User的resultMap-->
<resultMap id="userMap" type="user">
<id property="id" column="id"/>
<result property="username" column="username"/>
<result property="address" column="address"/>
<result property="sex" column="sex"/>
<result property="birthday" column="birthday"/>
<!-- 配置角色集合的映射 -->
<collection property="roles" ofType="role">
<id property="roleId" column="rid"/>
<result property="roleName" column="role_name"/>
<result property="roleDesc" column="role_desc"/>
</collection>
</resultMap>
<!-- 查询所有 -->
<select id="findAll" resultMap="userMap">
select u.*,r.id as rid,r.role_name,r.role_desc from user u
left outer join user_role ur on u.id = ur.uid
left outer join role r on r.id = ur.rid
</select>
</mapper>
(4)在UserDaoTest类中加入测试方法
package com.spg.dao;
import com.spg.entity.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.util.List;
public class UserDaoTest {
private InputStream in;
private SqlSession sqlSession;
private UserDao userDao;
@Before//用于在测试方法执行之前执行
public void init()throws Exception{
//1.读取配置文件,生成字节输入流
in = Resources.getResourceAsStream("mybatis-config.xml");
//2.获取SqlSessionFactory
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
//3.获取SqlSession对象
sqlSession = factory.openSession(true);
//4.获取dao的代理对象
userDao = sqlSession.getMapper(UserDao.class);
}
@After//用于在测试方法执行之后执行
public void destroy()throws Exception{
//提交事务
// sqlSession.commit();
//6.释放资源
sqlSession.close();
in.close();
}
/**
* 测试查询所有
*/
@Test
public void findAll(){
List<User> userList = userDao.findAll();
for(User user : userList){
System.out.println("每个用户的信息:");
System.out.println(user);
System.out.println(user.getRoles());
}
}
}
测试结果: