现有项目表(project),用户表(sys_user)。一个项目可以有很多人参与,一个人也可以同时处于多个项目。
一般对于这种 N 对 N 的关系,都会在数据库建立一个 中间表来维护关系,分别以两表的 ID 作为外键。
以下是 UserDO(sys_user 实体映射类):
@Data public class UserDO { /** * 主键 */ private String id; /** * 姓名 */ private String name; /** * 参与项目 */ private List<ProjectDO> projects; }ProjectDO(project 实体映射类)
@Data public class ProjectDO { /** * 主键 */ private String id; /** * 项目名称 */ private String name; /** * 参与者 */ private List<UserDO> users; }
在 resultMap 映射中,使用 collection 进行关联集合查询,这里不使用 select 标签进行关联查询,而是直接查询出来:
<?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.jiangchunbo.app.mapper.UserMapper"> <resultMap type="com.jiangchunbo.app.domain.UserDO" id="userResultMap"> <id column="id" property="id" /> <result column="name" property="name"/> <collection property="projects" ofType="com.jiangchunbo.app.domain.ProjectDO"> <id column="p.id" property="id" /> <result column="p.name" property="name" /> </collection> </resultMap> <sql id="userColumns"> u.id , u.name </sql> <sql id="projectColumns"> , p.id AS 'p.id' , p.name AS 'p.name' </sql> <select id="selectAll" resultMap="userResultMap"> SELECT <include refid="userColumns"/> <include refid="projectColumns"/> FROM sys_user u LEFT JOIN project_user pu ON u.id = pu.user_id LEFT JOIN project p ON p.id = pu.project_id </select> </mapper>在 resultMap 映射中,使用 collection 进行关联集合查询,同样,这里不使用 select 标签进行关联查询,而是直接查询出来:
<?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.jiangchunbo.app.mapper.ProjectMapper"> <resultMap type="com.jiangchunbo.app.domain.ProjectDO" id="projectResultMap"> <id column="id" property="id" /> <result column="name" property="name"/> <collection property="users" ofType="com.jiangchunbo.app.domain.UserDO"> <id column="u.id" property="id"/> <result column="u.name" property="name"/> </collection> </resultMap> <sql id="projectColumns"> p.id , p.name </sql> <sql id="userColumns"> , u.id AS 'u.id' , u.name AS 'u.name' </sql> <select id="selectAll" resultMap="projectResultMap"> SELECT <include refid="projectColumns"/> <include refid="userColumns"/> FROM project p LEFT JOIN project_user pu ON pu.project_id = p.id LEFT JOIN sys_user u ON u.id = pu.user_id </select> </mapper>