在 MyBatis 中實現一對多映射關系,通常需要通過嵌套查詢或者嵌套結果集來實現。以下是兩種常見的方式:
示例:
<select id="selectParent" resultType="Parent">
SELECT * FROM parent
</select>
<select id="selectChildren" resultType="Child">
SELECT * FROM child 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="selectParent" resultMap="parentMap">
SELECT p.*, c.* FROM parent p
LEFT JOIN child c ON p.id = c.parent_id
</select>
通過以上兩種方式可以實現一對多映射關系,開發人員可以根據具體的業務需求選擇合適的方式來實現。