[Mybatis] 查询数据某一字段为null,Mybatis映射问题

文章讲述了作者帮助同学解决SQL查询返回null的问题,分析了可能的原因,如字段名不匹配、查询条件错误、数据质量问题和MyBatis映射错误。提供了解决方案,包括更新实体类属性命名或使用resultMap进行字段映射。
摘要由CSDN通过智能技术生成

今天帮助同学解决一个查询数据为空的问题

sql如下

<select id="selectAll" resultType="com.example.entity.Sorders">
    select sorders.*, scope.avatar as scopeImg, scope.name as scopeName, user.name as userName
    from sorders
    left join scope on sorders.scope_id = scope.id
    left join user on sorders.user_id = user.id
    <where>
        <if test="id != null"> id= #{id}</if>
        <if test="sorderId != null"> and sorders.order_id = #{sorderId}</if>
        <if test="status != null"> and sorders.status= #{status}</if>
        <if test="scopeId != null"> and sorders.scope_id= #{scopeId}</if>
        <if test="userId != null"> and sorders.user_id= #{userId}</if>
        <if test="time != null"> and sorders.time= #{time}</if>
        <if test="inTime != null"> and sorders.in_time= #{inTime}</if>
        <if test="price != null"> and sorders.price= #{price}</if>
    </where>
    order by id desc
</select>

发现未查询到sorderId,经过debug定位到selectAll()方法返回数据为null,那问题应该就出现在SQL上

查询sorderId结果为null,即使数据库中存在相关数据,可能的原因包括以下几点:

  1. 字段名匹配问题

    如果在您的数据库表结构中,与sorders表相关的订单ID字段名并不是order_id,而是其他名字,那么就会导致查询不到正确的结果并返回null。
  2. 查询条件不匹配

    如果你在设置查询条件时,传递给#{sorderId}的值格式或内容不符合预期,比如使用了完全不匹配的字符串进行模糊查询,也可能导致查询不到数据。
  3. 数据质量问题

    虽然数据库中有数据,但如果sorders表中的order_id字段本身就是空(null),则查询结果自然会是null。
  4. MyBatis映射问题

    在MyBatis中,如果实体类(Sorders)中与order_id相对应的属性名不匹配,或者属性访问器(getter/setter)有误,也可能导致查询结果无法正确映射到实体对象中。

经过检查

实体类Sorders中与数据库表sordersorder_id字段相对应的属性名为sorderId而非orderId,则在MyBatis的映射配置文件中需要确保结果映射正确,让查询结果能够正确地绑定到实体类的属性上。

针对这种情况,有两种解决方法:

  1. 更新实体类属性命名

    将实体类中的属性名改为与数据库字段名相同的order_id,以保持一致性,这通常是最简单的做法,符合驼峰命名规范且能避免此类映射问题。
  2. 使用resultMap映射

    如果因为某种原因不能更改实体类的属性名,可以在MyBatis的XML映射文件中使用<resultMap>元素来显式指定数据库字段与实体类属性之间的映射关系:
    <resultMap id="sordersResultMap" type="com.example.entity.Sorders">
        <id property="sorderId" column="order_id"/>
        <!-- 其他字段映射 -->
    </resultMap>
    
    <select id="selectAll" resultMap="sordersResultMap">
        <!-- ... 查询语句不变 ... -->
    </select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

米开浪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值