我想重写我们的服务以使用 mybatis 映射和连接,使我们的实体在数据库/mybatis 层上完整并完成。
<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}
下一个问题是:如果父项没有子项,一些具有空值或默认字段的默认实体将被添加到列表中。 我明白这是outer join的本质,但是mybatis不是很聪明能理解这是假的吗?
有什么解决办法吗?我不能使用内部联接,因为父实体必须在结果中。
请您参考如下方法:
您必须将属性 notNullColumn
放入您的集合中。所以你的 resultMap 将是:
<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.id as ChildId