在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>
通過以上兩種方式,我們可以方便地處理一對多關系的數據,并在應用中使用。