<font color=black face="微软雅黑" size=3 >最近在使用Mybatis查询的时候,使用了BigDecimal类型的值进行查询,在控制台通过打印的sql发现,查询条件并没有拼接上去,导致查询失败。
为了演示还原这个过程,特意写了一个简单的演示项目:
比如:我现在查询product_price字段大于0的数据,数据库的数据如下所示:
mapper.xml中配置如下:
1<?xml version="1.0" encoding="UTF-8" ?> 2<!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 4<mapper namespace="com.example.mapper.ProductMapper"> 5 <select id="queryProductList" resultType="com.example.entity.Product" parameterType="com.example.entity.Product"> 6 select id id,product_name productName, product_price productPrice from sys_product where 1 = 1 7 <if test="id != null and '' != id"> 8 and id = #{id} 9 </if> 10 <if test="productName != null and '' != productName"> 11 and product_name = #{productName} 12 </if> 13 <if test="productPrice != null and '' != productPrice"> 14 and product_price >= #{productPrice} 15 </if> 16 </select> 17</mapper>
<font color=black face="微软雅黑" size=3 >通过一个简单的Controller进行测试:
1 @GetMapping("/query") 2 public List<Product> queryProductList() { 3 Product product = new Product(); 4 product.setProductPrice(new BigDecimal(0)); 5 return productService.getProduct(product); 6 }
启动项目:访问http://127.0.0.1:9999/springbatch/api/product/query
返回的数据如下:(返回了全部的数据,预期应该返回第一条的数据!!!)
再次查看控制台打印的sql,如下所示:显然没有拼接productPrice字段的查询条件。
我们如何进行解决呢?
我们只需要将mapper.xml文件中的productPrice字段的条件改为如下的方式:
1 <if test="productPrice != null"> 2 and product_price >= #{productPrice} 3 </if>
重启项目:再次访问测试接口,结果如下:返回了预期的数据,当然查询控制台打印的sql,也拼接上了查询条件。
<font color=red face="微软雅黑" size=2 > 2021年10月02日
