在 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> 通过以上两种方式可以实现一对多映射关系,开发人员可以根据具体的业务需求选择合适的方式来实现。