MyBatis--多表查询002

User类

public class User {    
    private int uid;
    private String name;

    private List<Account> accountList;
    private List<Role> roles;
}

Role类

public class Role {   
     private int rid;
    private String name;
    private String type;
    //角色里面有用户
    private List<User> userList;
}

RoleDao.xml

<collection>套娃

collection定义关联的集合类型的属性的封装规则:

property="rid":指定这是哪个集合类属性,这里为那个集合属性rid

ofType:指定集合内封装的JavaBean类型(集合内装的什么),这里即为Role类

ofType(自己定义类)指定的这个List所存放的javaBean的类型,比如这里就是User类型。

javaType(Java中已经定义好的)指定的当前这个配置的标签所对应的属性,比如我们这里的collection配置的是一个List

就可以配置成javaType=“java.util.ArrayList”

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cheng.dao.RoleDao">

    <resultMap id="roleMap" type="role">
        <id column="rid" property="rid"></id>
        <result column="name" property="name"></result>
        <result column="type" property="type"></result>
        <collection property="userList" ofType="user">
            <id column="uid" property="uid"></id>
            <result column="name" property="name"></result>
        </collection>
    </resultMap>

<!--    在查询时,MySQL中的表要建立外键约束连接-->
    <select id="findAllRole" resultMap="roleMap">
        select r.*,u.* from user u left join r_u_con ru on u.uid=ru.uid left join role r on ru.rid=r.rid

    </select>
</mapper>

Test类


public class Test {
    private InputStream in;
    private SqlSessionFactory factory;
    private SqlSession session;
    private RoleDao roleDaoMapper;

    @Before
    public void init() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        session = builder.build(in).openSession();
        roleDaoMapper = session.getMapper(RoleDao.class);

    }
    @After//在测试方法执行完成之后执行
    public void destroy() throws Exception{
        session.commit();
        session.close();
        in.close();
    }

    @org.junit.Test
    public void findAll(){
        List<Role> allRole = roleDaoMapper.findAllRole();
        for(Role role:allRole){
            System.out.println(role);
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值