在MyBatis中進行一對多關(guān)聯(lián)查詢可以通過在映射文件中使用嵌套查詢來實現(xiàn)。具體步驟如下:
<!-- 查詢主實體 -->
<select id="findMainEntity" resultType="MainEntity">
SELECT * FROM main_entity WHERE id = #{id}
</select>
<!-- 查詢從實體 -->
<select id="findSubEntities" resultType="SubEntity" parameterType="int">
SELECT * FROM sub_entity WHERE main_entity_id = #{id}
</select>
public class MainEntity {
private Long id;
private String name;
private List<SubEntity> subEntities;
// getter and setter methods
}
<resultMap id="MainEntityResult" type="MainEntity">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="subEntities" ofType="SubEntity" select="findSubEntities">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 其他從實體的屬性 -->
</collection>
</resultMap>
MainEntity mainEntity = sqlSession.selectOne("findMainEntity", 1);
通過以上步驟,就可以在MyBatis中實現(xiàn)一對多關(guān)聯(lián)查詢。在查詢主實體時,MyBatis會自動執(zhí)行嵌套查詢來獲取從實體的數(shù)據(jù),并將結(jié)果集合賦值給主實體的屬性,實現(xiàn)一對多關(guān)聯(lián)查詢。