一、问题
mybaits的xml中if判断integer或double等数值型,age=0时if条件不成立。
<if test="age!= null and age!= ''">
AND age= #{age}
</if>
二、验证
1、创建实体student
@Data
public class Student {
private String name;
private Integer age;
}
2、创建验证类
@RestController
@RequestMapping("/form/")
public class TestOgnl {
@Autowired
SqlSession sqlSession;
@RequestMapping("testOgnl")
public ApiResult test(){
Student student = new Student();
student.setAge(0);
ExpressionEvaluator evaluator = new ExpressionEvaluator();
DynamicContext context = new DynamicContext(sqlSession.getConfiguration(), student);
Boolean flag = evaluator.evaluateBoolean("age != null && age!=''",context.getBindings());
return ApiResult.success(flag);
}
}
3、结果当age=0时,flag=false;当age=1或不等于0的其他值,flag=true;
三、结论
mybatis 中 动态if 使用ognl表达式判断。当对象是Number类型,当传值为0时会被解析成false,否则为true,所以只有String类型使用!=‘’。