在MyBatis中处理一对多关系通常有两种方式:嵌套查询和嵌套结果。
<!-- 查询父对象 -->
<select id="selectParent" resultMap="parentMap">
SELECT * FROM parent_table WHERE id = #{parentId}
</select>
<!-- 查询子对象 -->
<select id="selectChildren" resultMap="childMap">
SELECT * FROM child_table WHERE parent_id = #{parentId}
</select>
<!-- 父对象和子对象的映射关系 -->
<resultMap id="parentMap" type="Parent">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="children" ofType="Child" resultMap="childMap"/>
</resultMap>
<resultMap id="childMap" type="Child">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
<!-- 查询父对象和子对象 -->
<select id="selectParentAndChildren" resultMap="parentAndChildrenMap">
SELECT p.id as parentId, p.name as parentName,
c.id as childId, c.name as childName
FROM parent_table p
LEFT JOIN child_table c ON p.id = c.parent_id
</select>
<!-- 父对象和子对象的映射关系 -->
<resultMap id="parentAndChildrenMap" type="Parent">
<id property="id" column="parentId"/>
<result property="name" column="parentName"/>
<collection property="children" ofType="Child">
<id property="id" column="childId"/>
<result property="name" column="childName"/>
</collection>
</resultMap>
通过以上两种方式,我们可以方便地处理一对多关系的数据,并在应用中使用。