mybatis 中collection嵌套collection引发的bug

本文探讨了MyBatis在处理多级关联映射时遇到的问题,特别是columnPrefix配置导致的子集合映射错误。通过调整SQL列前缀,解决了Parent对象中Child对象的Toy集合始终为空的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<resultMap id="ParentMap" type="org.example.mybatis.Parent">
    <id column="Id" jdbcType="VARCHAR" property="id" />
    <result column="Name" jdbcType="VARCHAR" property="name" />
    <result column="SurName" jdbcType="VARCHAR" property="surName" />

    <collection property="children"
        javaType="ArrayList" ofType="org.example.mybatis.Child"
        resultMap="ChildMap" columnPrefix="c_"/>    
   
</resultMap>

<resultMap id="ChildMap" type="org.example.mybatis.Child">
    <id column="Id" jdbcType="VARCHAR" property="id" />
    <result column="ParentId" jdbcType="VARCHAR" property="parentId" />
    <result column="Name" jdbcType="VARCHAR" property="name" />
    <result column="SurName" jdbcType="VARCHAR" property="surName" />
    <result column="Age" jdbcType="INTEGER" property="age" />

    <collection property="toys"
        javaType="ArrayList" ofType="org.example.mybatis.Toy"
        resultMap="ToyMap" columnPrefix="t_"/>   

</resultMap>

<resultMap id="ToyMap" type="org.example.mybatis.Toy">
    <id column="Id" jdbcType="VARCHAR" property="id" />
    <result column="ChildId" jdbcType="VARCHAR" property="childId" />
    <result column="Name" jdbcType="VARCHAR" property="name" />
    <result column="Color" jdbcType="VARCHAR" property="color" />
</resultMap>

<sql id="Parent_Column_List">
    p.Id, p.Name, p.SurName,
</sql>  

<sql id="Child_Column_List">
    c.Id as c_Id, c.ParentId as c_ParentId, c.Name as c_Name, c.SurName as c_Surname, c.Age as c_Age,
</sql>

<sql id="Toy_Column_List">
    t.Id as t_Id, t.Name as t_Name, t.Color as t_Color
</sql>  

<select id="getParent" parameterType="java.lang.String" resultMap="ParentMap" >
    select 
    <include refid="Parent_Column_List"/>
    <include refid="Child_Column_List" />
    <include refid="Toy_Column_List" />
    from Parent p

    left outer join Child c on p.Id = c.ParentId
    left outer join Toy t on c.Id = t.ChildId
    where p.id = #{id,jdbcType=VARCHAR}
</select>

表面来看没有任何问题 实际 查询的child对象中的toys一直是空

类关系介绍:

  • Parent类有属性ArrayList<Child> children
  • Child类有属性ArrayList<Toy> toys
  • Toy是一个普通的类

原因在于:

<collection property="toys"
        javaType="ArrayList" ofType="org.example.mybatis.Toy"
        resultMap="ToyMap" columnPrefix="t_"/>   

columnPrefix配置的是t_实际mybatis处理后是 c_t_

解决办法:只需要修改 sql 修改前缀为 c_t_ 即可

<sql id="Toy_Column_List">
    t.Id as c_t_Id, t.Name as c_t_Name, t.Color as c_t_Color
</sql>  

 

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值