MyBatis查询报错:Expected one result (or null) to be returned by selectOne(), but found: 2

MyBatis在查询数据时,查询涉及到多张表,且查询的对象存在集合的属性时,如下查询会报错:Expected one result (or null) to be returned by selectOne(), but found: 2

<resultMap id="classesMap" type="cn.jam.entity.Classes">
    <id column="c.id" property="id"/>
    <result column="c.name" property="name"/>
    <collection property="students" ofType="cn.jam.entity.Student">
        <id column="s.id" property="id"/>
        <result column="s.name" property="name"/>
    collection>
resultMap>

<select id="findById" parameterType="long" resultMap="classesMap">
    select c.id, c.name, s.id, s.name
    from t_classes c
    left join t_student s
    on c.id = s.cid
    where c.id = #{id};
select>

原因在于 c.id, c.name, s.id, s.name这几列没有定义别名,导致在根据resultMap生成对象时生成了多条,至于其中的原因暂时还没有深挖。

修改成下面的写法就没有问题了。

<resultMap id="classesMap" type="cn.jam.entity.Classes">
    <id column="cid" property="id"/>
    <result column="cname" property="name"/>
    <collection property="students" ofType="cn.jam.entity.Student">
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
    collection>
resultMap>

<select id="findById" parameterType="long" resultMap="classesMap">
    select c.id as cid, c.name as cname, s.id as sid, s.name as sname
    from t_classes c
    left join t_student s
    on c.id = s.cid
    where c.id = #{id};
select>

你可能感兴趣的:(踩坑,mybatis,java,bug)