MyBatis 配置之关联的嵌套
0x00:前言介绍
在 MyBatis 的 resultMap 输出映射配置中,当映射 type 为 Java 包装类时,可能会遇到包装类中含有其他 Java 包装类的属性,这里 resultMap 提供了 association 标签来定义结果集中包含的结果集。
0x01:代码示例
例如一个购物车示例,在查询购物车时关联了购物车的用户信息,其中购物车 ShoppingCart 的包装类代码如下:
package cn.com.mybatis.pojo; public class ShoppingCart{ //购物车id private int scartid; //购物车商品名 private String pname; //购物车关联的用户 private User user; //购物车其他属性... //get和set方法 }
在对查询结果进行映射时包含了一个用户的映射配置:
<resultMap id="shoppingResult" type="cn.com.mybatis.pojo.ShoppingCart"> <id property="scartid" column="cart_id"/> <result property="pname" column="product_name"/> <association property="id" column="product_name"/> <id property="id" column="user_id"/> <result property="username" column="user_username"/> <result property="gender" column="user_gender"/> <result property="email" column="user_email"/> </association> </resultMap> <select id="queryShoppingCart" parameterType="int" resultMap="shoppingResult"> select S.id as cart_id, S.name as product_name, S.userid as cart_user_id, U.id as user_id, U.username as user_username, U.gender as user_gender, U.email as user_email from shoppingcart S left outer join user U on S.userid = U.id where S.id = #{id} </select>
最终通过 resultMap 拿到的查询结果,是一个包含 user 对象信息的 ShoppingCart 包装类。
0x02:外部引用
如果之前定义好了 user 的 resultMap,那么可以在查询结果集配置中引入外部的 resultMap 来使用,配置方式一样,也是使用 association 标签,只不过多设置一个 resultMap 的属性指向外部的 resultMap 标签的 id。配置示例代码如下:
<resultMap id="shoppingResult" type="cn.com.mybatis.pojo.ShoppingCart"> <id property="scartid" column="cart_id"> <result property="pname" column="product_name"/> <association property="user" column="cart_user_id" javaType="User" resultMap="userResultMap"/> </resultMap> <resultMap id="userResult" type="User"> <id property="id" column="user_id"/> <result property="username" column="user_username"/> <result property="gender" column="user_gender"/> <result property="email" column="user_email"/> </resultMap>
0x03:总结
当 MyBatis 映射类型是包装类时,且包装类中还含有其他包装类中的属性,就需要用到 resultMap 中的 association 标签来定义结果集中包含的结果集。对于 association 可以在标签中配置,也可以从外部引用。
公众号回复数字“8”领取CIS加固全套手册。
微 信:fageweiketang,朋友圈不定期干货分享,欢迎讨论。
公众号:发哥微课堂,专注于代码审计、WEB渗透、网络安全。
专注于代码审计、WEB渗透、网络安全和运维