最近在使用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日

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐