MyBatis 实现一对多关联查询通常有以下几种方式:
1. 嵌套查询(Nested Queries):
这种方式通过在主查询中嵌套子查询,实现一对多的关联查询。比如,在父对象(一)的查询语句中嵌套子对象(多)的查询语句,通过外键关联父子对象。
示例:
<select id="selectParentWithChildren" resultMap="parentResultMap">
SELECT parent.id as parent_id, parent.name as parent_name,
child.id as child_id, child.info as child_info
FROM parent_table parent
LEFT JOIN child_table child ON parent.id = child.parent_id
</select>
2. 嵌套结果映射(Nested Result Maps):
这种方式通过定义多个结果映射,让 MyBatis 在执行查询时,自动将多个结果集映射到对象的嵌套属性中。
示例:
<!-- 定义父对象的映射 -->
<resultMap id="parentResultMap" type="ParentEntity">
<id property="id" column="parent_id"/>
<result property="name" column="parent_name"/>
<!-- 嵌套子对象的映射 -->
<collection property="children" ofType="ChildEntity">
<id property="id" column="child_id"/>
<result property="info" column="child_info"/>
</collection>
</resultMap>
<!-- SQL 查询语句 -->
<select id="selectParentWithChildren" resultMap="parentResultMap">
SELECT parent.id as parent_id, parent.name as parent_name,
child.id as child_id, child.info as child_info
FROM parent_table parent
LEFT JOIN child_table child ON parent.id = child.parent_id
</select>
3. 使用 MyBatis 的一对多关联映射(Association 和 Collection):
可以通过 MyBatis 的 <association>
和 <collection>
标签,显式定义父子对象之间的关联关系和映射。
示例:
<select id="selectParentWithChildren" resultMap="parentResultMap">
SELECT parent.id as parent_id, parent.name as parent_name,
child.id as child_id, child.info as child_info
FROM parent_table parent
LEFT JOIN child_table child ON parent.id = child.parent_id
</select>
<resultMap id="parentResultMap" type="ParentEntity">
<id property="id" column="parent_id"/>
<result property="name" column="parent_name"/>
<!-- 使用 <collection> 定义一对多关联映射 -->
<collection property="children" ofType="ChildEntity" select="selectChildrenByParentId">
<id property="id" column="child_id"/>
<result property="info" column="child_info"/>
</collection>
</resultMap>
<select id="selectChildrenByParentId" parameterType="long" resultType="ChildEntity">
SELECT id, info
FROM child_table
WHERE parent_id = #{id}
</select>
以上是常用的几种方式,根据具体业务需求和数据结构的复杂度,选择合适的方式来实现一对多的关联查询。