在多对多关系中用用户和角色模型来模拟
一个用户可以用多个角色
一个角色可以被多人拥有
角色表:
用户表:
用户与角色的中间表
这里使用另外一种方法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()); } } }