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);
}
}
}