mybatis復雜對象查詢
1、一對多查詢
<resultMap type="com.cdxt.ds.web.lesson.pojo.CourseInfo" id="courseDetailInfo" >
<id column="courseID" property="courseID"/>
<result column="price" property="price"/>
<result column="name" property="name"/>
<result column="totalclass" property="totalClass"/>
<result column="type" property="type"/>
<result column="brief" property="brief"/>
<collection property="coursePlan" ofType="com.cdxt.ds.web.lesson.pojo.CoursePlan">
<id column="courseID" property="id"/>
<result column="classnumber" property="classNumber"/>
<result column="time" property="time"/>
</collection>
</resultMap>
<!-- 查詢課程信息單一記錄 -->
<select id="getCourseInfobyCpurseID" parameterType="int" resultMap="courseDetailInfo">
select a.courseID,a.price,a.name,a.totalclass,a.type,a.brief,b.id,
b.classnumber,b.time from XTEL_COURSEINFO a left join XTEL_CourseArrangement b
on a.courseID=b.courseID where a.COURSEID=#{cpurseID}
</select>
問題:測試的時候發現只能從表只能查詢到一條記錄。
原因:兩張表主鍵一樣,出現的數據覆蓋
解決方法:
1、修改數據庫id,不推薦
2、查詢結果起別名
<resultMap type="com.cdxt.ds.web.lesson.pojo.CourseInfo" id="courseDetailInfo" > <id column="courseID" property="courseID"/> <result column="price" property="price"/> <result column="name" property="name"/> <result column="totalclass" property="totalClass"/> <result column="type" property="type"/> <result column="brief" property="brief"/> <collection property="coursePlan" ofType="com.cdxt.ds.web.lesson.pojo.CoursePlan"> <id column="courseID" property="id"/> <result column="classnumber" property="classNumber"/> <result column="time" property="time"/> </collection> </resultMap> <!-- 查詢課程信息單一記錄 --> <select id="getCourseInfobyCpurseID" parameterType="int" resultMap="courseDetailInfo"> select a.courseID,a.price,a.name,a.totalclass,a.type,a.brief,b.courseID id, b.classnumber,b.time from XTEL_COURSEINFO a left join XTEL_CourseArrangement b on a.courseID=b.courseID where a.COURSEID=#{cpurseID} </select>
mybatis復雜對象查詢