MyBatis(3.2.3) - One-to-one mapping using nested ResultMap
We can get Student along with the Address details using a nested ResultMap as follows:
<resultMap type="Address" id="AddressResult"> <id property="addrId" column="addr_id"/> <result property="street" column="street"/> <result property="city" column="city"/> <result property="state" column="state"/> <result property="zip" column="zip"/> <result property="country" column="country"/> </resultMap> <resultMap type="Student" id="StudentWithAddressResult"> <id property="studId" column="stud_id"/> <result property="name" column="name"/> <result property="email" column="email"/> <association property="address" resultMap="AddressResult"/> </resultMap> <select id="selectStudentWithAddress" parameterType="int" resultMap="StudentWithAddressResult"> SELECT STUD_ID, NAME, EMAIL, PHONE, A.ADDR_ID, STREET, CITY, STATE, ZIP, COUNTRY FROM STUDENTS S LEFT OUTER JOIN ADDRESSES A ON S.ADDR_ID = A.ADDR_ID WHERE STUD_ID = #{studId} </select>
The <association> element can be used to load the has-one type of associations. In the preceding example, we used the <association> element, referencing another <resultMap> that is declared in the same XML file.
We can also use <association> with an inline resultMap query as follows:
<resultMap type="Student" id="StudentWithAddressResult"> <id property="studId" column="stud_id"/> <result property="name" column="name"/> <result property="email" column="email"/> <association property="address" javaType="Address"> <id property="addrId" column="addr_id"/> <result property="street" column="street"/> <result property="city" column="city"/> <result property="state" column="state"/> <result property="zip" column="zip"/> <result property="country" column="country"/> </association> </resultMap>
Using the nested ResultMap approach, the association data will be loaded using a single query (along with joins if required).
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步