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

简介: 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日

相关文章
|
5天前
|
Java 数据库连接 数据库
mybatis查询数据,返回的对象少了一个字段
mybatis查询数据,返回的对象少了一个字段
28 8
|
6天前
|
SQL XML Java
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
文章介绍了MyBatis中高级查询的一对多和多对一映射处理,包括创建数据库表、抽象对应的实体类、使用resultMap中的association和collection标签进行映射处理,以及如何实现级联查询和分步查询。此外,还补充了延迟加载的设置和用法。
mybatis复习04高级查询 一对多,多对一的映射处理,collection和association标签的使用
|
5月前
|
SQL Java 关系型数据库
Mybatis多表关联查询与动态SQL(下)
Mybatis多表关联查询与动态SQL
114 0
|
3月前
|
Java 数据库连接 mybatis
Mybatis查询传递单个参数和传递多个参数用法
Mybatis查询传递单个参数和传递多个参数用法
52 11
MybatisPlus-标准CRUD制作,新增boolean save(T t),删除 ~ delete(int id),修改 ~ update(T t),根据id查询,T getById....
MybatisPlus-标准CRUD制作,新增boolean save(T t),删除 ~ delete(int id),修改 ~ update(T t),根据id查询,T getById....
MyBatisPlus如何根据id批量查询?Required request parameter ‘id‘ for method 解决方法是看青戈大佬MybatisPlus的教程
MyBatisPlus如何根据id批量查询?Required request parameter ‘id‘ for method 解决方法是看青戈大佬MybatisPlus的教程
MybatisPlus介绍新增用户,根据id查询,引入MybatisPlus的起步依赖,增删改查最简单的写法
MybatisPlus介绍新增用户,根据id查询,引入MybatisPlus的起步依赖,增删改查最简单的写法
|
4月前
|
Java 数据库连接 mybatis
Mybatis基于注解的一对一和一对多查询
Mybatis基于注解的一对一和一对多查询
|
5月前
|
算法 BI 数据库
MyBatisPlus查询条件设置、映射匹配兼容性、id生成策略、多数据操作
MyBatisPlus查询条件设置、映射匹配兼容性、id生成策略、多数据操作
203 3
|
5月前
|
SQL Java 数据库连接
MyBatis 查询数据库
MyBatis 查询数据库