我想重写我们的服务以使用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}
接下来的问题是:如果父级没有子级,则某些具有null或默认字段的默认实体将添加到列表中。
我知道这是外部联接的性质,但是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