Mybatis select返回多个list,但为啥只有一条记录

问题描述

本人做一个SSM项目,发现查询数据库数据,sql没有错,在Navicat中查询也是没有问题,但 返回数据只有一条,很奇怪,看网上教程,也都是差不多的教程,按理说我的mapper文件是没错的,因为其他一样的查询却可以查询出多条数据,同样的mapper写法。

解决方法

我对比了一下两者之间的sql差异,发现可能是在mapper中返回的字段比sql中多,再想是不是这个原因造成的,也有可能是主键id索引造成,结果就返回一条数据,本着动手的能力,本人就采取以下两种方案:

  • 方案一在之前的select后面加上主键id
    <resultMap id="orderResultMap" type="com.bean.PurchaseRecord">
        <id column="id" jdbcType="SMALLINT" property="id" />
        <result column="user_id" jdbcType="SMALLINT" property="userId" /> 
        <result column="commodity_id" jdbcType="SMALLINT" property="commodityId" />
        <result column="commodity_num" jdbcType="SMALLINT" property="commodityNum" />
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
        <association property="commodity" column="commodityId"
            javaType="com.bean.Commodity" jdbcType="SMALLINT" resultMap="GoodResultMap">
        </association>
    </resultMap>

    <select id="selectForAll" resultMap="orderResultMap">
        SELECT purchase_record.id,purchase_record.commodity_id,commodity.url,commodity.title,
        commodity.price,purchase_record.commodity_num,purchase_record.create_time 
        from commodity,purchase_record
        WHERE commodity.id=purchase_record.commodity_id
    </select>

注意SELECT单词后面 添加了 id,查询结果正确。

  • 方案二 去掉不返回的字段定义
    在resultMap中定义了很多不返回的字段,比如 id,user_id等,于是去掉这些字段,测试也是正确的。
<resultMap id="orderResultMap" type="com.bean.PurchaseRecord">
        <result column="commodity_id" jdbcType="SMALLINT" property="commodityId" />
        <result column="commodity_num" jdbcType="SMALLINT" property="commodityNum" />
        <result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
        <result column="update_time" jdbcType="TIMESTAMP" property="updateTime" />
        <association property="commodity" column="commodityId"
            javaType="com.bean.Commodity" jdbcType="SMALLINT" resultMap="GoodResultMap">
        </association>
    </resultMap>

    <select id="selectForAll" resultMap="orderResultMap">
        SELECT purchase_record.id,purchase_record.commodity_id,commodity.url,commodity.title,
        commodity.price,purchase_record.commodity_num,purchase_record.create_time 
        from commodity,purchase_record
        WHERE commodity.id=purchase_record.commodity_id
    </select>

总结

可能是本人书写不规范,造成这个问题,不过也很奇怪,目前学习的mybatis知识太少,还要继续学习,更深入的原因后面也要继续学习。

猜你喜欢

转载自blog.csdn.net/randompeople/article/details/79631261