动态sql之 if 标签

    <select id="quaryByName1" resultType="com.example.springboormybatis.mybatis.entity.Student">
        select * from student
        where 1=1
        <if test="name != '' and name != null">
            and `name` like "%" #{
    
    name} "%"
        </if>
        <if test="age != null">
            and `age` = #{
    
    age}
        </if>
    </select>

注意:
使用动态sql的时候dao接口的形参要使用Java对象.如果springboot中不使用Java对象传参,需要用到@RequestParam注解的required = false属性,使其为非必传字段,这样dao接口就可以使用多个简单类型的形参了.
controller层:

    public List<Student> quaryByName1(@RequestParam(value = "name",required = false) String name,@RequestParam(value = "age",required = false) Integer age){
    
    
        return crudService.quaryByName1(name,age);
    }

dao接口:

    List<Student> quaryByName1(@Param("name") String name,@Param("age") Integer age);

额外说明下:
上诉代码的Integer 换成int就会报错java.lang.IllegalStateException
如果dao接口入参是java对象,简单数据类型会默认他的默认值,String默认null,int默认0.Java中8种基本数据类型及其默认值

    public List<Student> quaryByName1(Student student){
    
    
        return crudService.quaryByName1(student);
    }

猜你喜欢

转载自blog.csdn.net/weixin_55806809/article/details/121278155