Mybatis一对多集合映射始终具有一个默认实体 [英] Mybatis one-to-many collection mapping always have one default entity
问题描述
我想重写我们的服务以使用mybatis映射和连接来使我们的实体在数据库/ mybatis层上完整并完成。
I want to rewrite our services to use mybatis mapping and joins to have our entity full and completed on database/mybatis layer.
<resultMap id="ParentMap" type="org.example.mybatis.Parent">
<id column="id" jdbcType="VARCHAR" property="id" />
<id column="Name" jdbcType="VARCHAR" property="name" />
<id column="SurName" jdbcType="VARCHAR" property="surName" />
<collection property="childs" column="ChildId"
javaType="ArrayList" ofType="org.example.mybatis.Child"
resultMap="org.example.ChildMap" />
</resultMap>
<resultMap id="ChildMap" type="org.example.mybatis.Parent">
<id column="id" jdbcType="VARCHAR" property="id" />
<id column="Name" jdbcType="VARCHAR" property="name" />
<id column="SurName" jdbcType="VARCHAR" property="surName" />
<id column="Age" jdbcType="INTEGER" property="age" />
</resultMap>
<sql id="Parent_Column_List">
p.Id, p.Name, p.SurName,
</sql>
<sql id="Child_Column_List">
c.Id, c.ParentId c.Name, c.SurName, c.Age
</sql>
<select id="getParent" parameterType="java.lang.String" resultMap="ParentMap" >
select
<include refid="Parent_Column_List"/>
<include refid="Child_Column_List" />
from Parent p
left outer join Child c on p.Id = c.ParentId
where p.id = #{id,jdbcType=VARCHAR}
问题是下一个:如果父母没有孩子,一些带有null或default字段的默认实体将被添加到列表中。
我明白这是外连接的本质,但mybatis不是很聪明地明白这是假的吗?
Problem is next: if parent doesn't has childs, some default entity with null or default fields will be added to list. I understand that this is nature of outer join, but is mybatis not very clever to understand that this is fake?
是否有一些解决方法?我不能使用内连接,因为父实体必须在结果中。
Is there some workaround about this? I cannot use inner join since parent entity is required to be in result.
推荐答案
你必须把属性 notNullColumn
在你的收藏中。所以你的resultMap将是:
You have to put the attribute notNullColumn
in your collection. So your resultMap will be:
<resultMap id="ParentMap" type="org.example.mybatis.Parent">
<id column="id" jdbcType="VARCHAR" property="id" />
<id column="Name" jdbcType="VARCHAR" property="name" />
<id column="SurName" jdbcType="VARCHAR" property="surName" />
<collection property="childs" column="ChildId" notNullColumn="id"
javaType="ArrayList" ofType="org.example.mybatis.Child"
resultMap="org.example.ChildMap" />
</resultMap>
请注意,您可能还会遇到两个 id $的问题c $ c>,所以你可能必须在你的选择
Note that you will also maybe have issues with the two id
, so you will maybe have to have a c.id as ChildId
in your select
这篇关于Mybatis一对多集合映射始终具有一个默认实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!