在MyBatis中進行一對多關聯查詢可以通過在映射文件中使用嵌套查詢來實現。具體步驟如下:
<!-- 查詢主實體 -->
<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中實現一對多關聯查詢。在查詢主實體時,MyBatis會自動執行嵌套查詢來獲取從實體的數據,并將結果集合賦值給主實體的屬性,實現一對多關聯查詢。