mybatis复杂对象查询

Posted 小哥z

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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复杂对象查询的主要内容,如果未能解决你的问题,请参考以下文章

mybatis复杂对象查询

Mybatis复杂查询动态sql及缓存详解

MyBatis高级特性

查询复杂对象用respsbody转换成json串时,mybatis的延迟加载报错的解决方法

SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper

Mybatis--02