使用Mybatis 对数据库进行一对多嵌套结果查询,报错?

部分代码

【因为项目代码较多,且题主不知道什么原因导致报错,故将项目完整放在和彩云以方便排错
链接: https://caiyun.139.com/m/i?0d... 提取码:hSdd 】
image.pngimage.pngimage.png

sql映射文件
<mapper namespace="Student1">
    <select id="selectBlog" resultMap="T">
        select stu_table.name,tea_table.tea_name
        from stu_table,tea_table
        where stu_table.tid=tea_table.tea_id and tea_table.tea_id=#{id};
    </select>

    <!--起别名 column映射数据库列名|property映射实体类属性名【均不区分大小写】-->
    <resultMap id="T" type="Teacher">
        <id column="tea_id" property="tea_ID"/>
        <result column="tea_name" property="NAME"/>
        <collection property="student" ofType="Student">
            <id column="stu_id" property="ID"/>
            <result column="name" property="NAME"/>
        </collection>
    </resultMap>

问题

使用Mybatis 对数据库进行一对多嵌套结果查询,当id设1时一切正常,当id=2时报错信息大致如下:

Exception in thread "main" org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 4
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:80)
    at StudentDao.getTeacher(StudentDao.java:9)
    at Text.main(Text.java:9)

数据库结构及参数设置

数据库结构
image.pngimage.png
代码全部参考于https://edu.aliyun.com/lesson...视频【问题代码约在视频第15:00~17:00处】,题主已按照视频中的代码进行了排错,但是不幸错误依然存在

运行环境

interllij开发版2021.3
jdk1.8
mysql及其gui
mybatis框架
该项目为基于maven的Javaweb项目

个人对报错信息初步分析

通过对idea报错信息的分析及百度,目前可以确定报错信息应该是与selectOne()只能返回一个参数有关,但是,视频中代码应用的就是selectOne()方法,但其运行一切正常,目前题主不知如何排错,如图,大约在视频第11:20左右
image.png

阅读 2.8k
1 个回答

image.png
应该是select stu_table.*, tea_table.*

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进