Mybatis one-to-many collection display always has one default object

I want to rewrite our services to use mybatis mapping and union so that our entity is populated and populated at the / mybatis database level.

<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} 

The problem is this: if the parent has no children, some default object with zero or default fields will be added to the list. I understand that this is the appearance of the external connection, but does mybatis mind really understand that this is a fake?

Is there a workaround for this? I cannot use the inner join, since the parent must be the result.

+4
source share
2 answers

You must put the notNullColumn attribute 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> 

Please note that you may also have problems with two id , so you may need c.id as ChildId in the selected

+14
source

This should work by default. No need to add notNullColumn .

MyBatis detects empty objects by default.

I just included this test in the project, please take a look at it.

Code

0
source

Source: https://habr.com/ru/post/1441774/


All Articles