<collection>映射集合结果查询
实体类
private String id;//主键 private String userName;//用户姓名 private List<Article> articleList;
方式一:通过<collection>封装结果集
<resultMap id="BaseRoleResultMap" type="cn.com.hellowood.springsecurity.model.RoleModel"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="is_active" property="isActive" jdbcType="BOOLEAN"/> <result column="description" property="description" jdbcType="VARCHAR"/> <result column="last_update_time" property="lastUpdateTime" jdbcType="TIMESTAMP"/> <collection property="menus" ofType="cn.com.hellowood.springsecurity.model.MenuModel" javaType="java.util.ArrayList"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="value" property="value" jdbcType="VARCHAR"/> <result column="display_value" property="displayValue" jdbcType="VARCHAR"/> <result column="url" property="url" jdbcType="VARCHAR"/> <result column="category" property="category" jdbcType="INTEGER"/> <result column="description" property="description" jdbcType="VARCHAR"/> <result column="is_active" property="isActive" jdbcType="BIT"/> <result column="last_update_time" property="lastUpdateTime" jdbcType="TIMESTAMP"/> </collection> </resultMap>
查询:
<select id="getRoles" parameterType="java.lang.Integer" resultMap="BaseRoleResultMap"> SELECT r.id,r.name,r.description,r.is_active,r.last_update_time,m.id,m.value,m.display_value,m.url,m.category,m.description,m.is_active,m.last_update_time FROM role r LEFT JOIN role_menu_xref rmx ON r.id = rmx.role_id LEFT JOIN menu m ON m.id = rmx.menu_id WHERE r.id = #{roleId,jdbcType=INTEGER} </select>
方式二:通过<collection>标签实现分段查找
<resultMap id="BaseRoleResultMap" type="cn.com.hellowood.springsecurity.model.RoleModel"> <id column="id" property="id" jdbcType="INTEGER"/> <result column="name" property="name" jdbcType="VARCHAR"/> <result column="is_active" property="isActive" jdbcType="BOOLEAN"/> <result column="description" property="description" jdbcType="VARCHAR"/> <result column="last_update_time" property="lastUpdateTime" jdbcType="TIMESTAMP"/> <collection property="menus" ofType="cn.com.hellowood.springsecurity.model.menus" javaType="java.util.ArrayList" select="getMenus" column="id"></collection> </resultMap>
对应的Mapper映射文件:
<select id="getMenus" parameterType="java.lang.Integer" resultMap="BaseMenuResultMap"> SELECT m.id,m.value,m.display_value,m.url,m.category,m.description,m.is_active,m.last_update_time FROM menu m LEFT JOIN role_menu_xref rmx ON m.id = rmx.menu_id WHERE role_id = #{roleId, jdbcType=INTEGER} </select>
查询:
<select id="getEmpByIdStep" resultMap="BaseRoleResultMap"> select * from role_model where id=#{id} </select>
<collection/>参数说明
- collection : 一个复杂的类型关联,许多结果将映射为这种类型
- property : 这是关联的 JavaBean 中的属性名, 在 RoleModel 中对应 private List<MenuModel> menus;
- javaType : property 属性对应的集合类型
- ofType : property 集合中的泛型,在 RoleModel 中是 MenuModel
- column : RoleModel 的 id ,作为参数传入被调用的 Select 语句
- select : 另外一个映射语句的 ID