Mybatis 多表查询之多对多

在多对多关系中用用户和角色模型来模拟

一个用户可以用多个角色

一个角色可以被多人拥有

角色表:

用户表:

用户与角色的中间表

这里使用另外一种方法resultMap,定义专门的 resultMap 用于映射一对一查询结果。
 

创建用户Role的实体类

拥有属性

private int roleId;
private String roleName;
private String roleDesc;
private List<User> users;

创建持久层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.itylm.dao.RoleDao">
    <!--定义 role 表的 ResultMap-->
    <resultMap id="roleMap" type="com.itylm.domain.Role">
        <id property="roleId" column="rid"></id>
        <result property="roleName" column="role_name"></result>
        <result property="roleDesc" column="role_desc"></result>
        <collection property="users" ofType="com.itylm.domain.User">
            <id column="id" property="id"></id>
            <result column="username" property="username"></result>
            <result column="address" property="address"></result>
            <result column="sex" property="sex"></result>
            <result column="birthday" property="birthday"></result>
        </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>

进行测试

public class Demo4 {

        private InputStream in;
        private SqlSession sqlSession;
        private RoleDao roleDao;

        @Before//用于在测试方法执行之前执行
        public void init() throws Exception {
            //1.读取配置文件,生成字节输入流
            in = Resources.getResourceAsStream("SqlMapConfig.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 testFindAll() {
            List<Role> roles = roleDao.findAll();
            for (Role role : roles) {
                System.out.println("---每个角色的信息----");
                System.out.println(role);
                System.out.println(role.getUsers());
            }
        }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值