今天帮助同学解决一个查询数据为空的问题
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,即使数据库中存在相关数据,可能的原因包括以下几点:
-
字段名匹配问题:
如果在您的数据库表结构中,与sorders表相关的订单ID字段名并不是order_id,而是其他名字,那么就会导致查询不到正确的结果并返回null。 -
查询条件不匹配:
如果你在设置查询条件时,传递给#{sorderId}的值格式或内容不符合预期,比如使用了完全不匹配的字符串进行模糊查询,也可能导致查询不到数据。 -
数据质量问题:
虽然数据库中有数据,但如果sorders表中的order_id字段本身就是空(null),则查询结果自然会是null。 -
MyBatis映射问题:
在MyBatis中,如果实体类(Sorders)中与order_id相对应的属性名不匹配,或者属性访问器(getter/setter)有误,也可能导致查询结果无法正确映射到实体对象中。
经过检查
实体类Sorders中与数据库表sorders的order_id字段相对应的属性名为sorderId而非orderId,则在MyBatis的映射配置文件中需要确保结果映射正确,让查询结果能够正确地绑定到实体类的属性上。
针对这种情况,有两种解决方法:
-
更新实体类属性命名:
将实体类中的属性名改为与数据库字段名相同的order_id,以保持一致性,这通常是最简单的做法,符合驼峰命名规范且能避免此类映射问题。 -
使用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>
文章讲述了作者帮助同学解决SQL查询返回null的问题,分析了可能的原因,如字段名不匹配、查询条件错误、数据质量问题和MyBatis映射错误。提供了解决方案,包括更新实体类属性命名或使用resultMap进行字段映射。
1479

被折叠的 条评论
为什么被折叠?



