Mybatis查询的时候BigDecimal类型的值查询失效的解决办法

最近在使用Mybatis查询的时候,使用了BigDecimal类型的值进行查询,在控制台通过打印的sql发现,查询条件并没有拼接上去,导致查询失败。
为了演示还原这个过程,特意写了一个简单的演示项目:
比如:我现在查询product_price字段大于0的数据,数据库的数据如下所示:
在这里插入图片描述
mapper.xml中配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.ProductMapper">
    <select id="queryProductList" resultType="com.example.entity.Product" parameterType="com.example.entity.Product">
        select id id,product_name productName, product_price productPrice from sys_product where 1 = 1
        <if test="id != null and '' != id">
            and id = #{id}
        </if>
        <if test="productName != null and '' != productName">
            and product_name = #{productName}
        </if>
        <if test="productPrice != null  and '' != productPrice">
            and product_price &gt;= #{productPrice}
        </if>
    </select>
</mapper>

通过一个简单的Controller进行测试:

 @GetMapping("/query")
    public List<Product> queryProductList() {
        Product product = new Product();
        product.setProductPrice(new BigDecimal(0));
        return productService.getProduct(product);
    }

启动项目:访问http://127.0.0.1:9999/springbatch/api/product/query
返回的数据如下:(返回了全部的数据,预期应该返回第一条的数据!!!)
在这里插入图片描述
再次查看控制台打印的sql,如下所示:显然没有拼接productPrice字段的查询条件。
在这里插入图片描述
我们如何进行解决呢?
我们只需要将mapper.xml文件中的productPrice字段的条件改为如下的方式:

  <if test="productPrice != null">
       and product_price &gt;= #{productPrice}
  </if>

重启项目:再次访问测试接口,结果如下:返回了预期的数据,当然查询控制台打印的sql,也拼接上了查询条件。
在这里插入图片描述
在这里插入图片描述
2021年10月02日

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小小Java开发者

“是一种鼓励,你懂的”

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

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

打赏作者

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

抵扣说明:

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

余额充值