动态SQL

1.if标签:多条件查询。
 

    List selectByMultiCondition(@Param("brand") String brand, @Param("guidePrice") Double guidePrice, @Param("carType") String carType);
    

2.where标签:是专门负责where子句动态生成的 ,让where⼦句更加动态智能。
        所有条件都为空时,where标签保证不会⽣成where⼦句。
        ⾃动去除某些条件前⾯多余的and或or。但是后⾯多余的and是不会被去除的。

   

3.trim标签:

    

4. set标签:
主要使⽤在update语句当中,⽤来⽣成set关键字,同时去掉最后多余的“,”
⽐如我们只更新提交的不为空的字段,如果提交的数据是空或者"",那么这个字段我们将不更新。

   
        update t_car
        
            car_num = #{carNum},
            brand = #{brand},
            guide_price = #{guidePrice},
            produce_time = #{produceTime},
            car_type = #{carType},
        
        where
            id = #{id}
    

5. choose when otherwise标签:相当于if(){} else if(){} else{} 只有一个标签会被选择!


    

6. foreach标签:
循环数组或集合,动态⽣成sql:一般用来进行批量删除和批量添加:

foreach标签的属性:
    collection:指定数组或者集合
    item:代表数组或集合中的元素
    separator:循环之间的分隔符
    open: foreach循环拼接的所有sql语句的最前面以什么开始。
    close: foreach循环拼接的所有sql语句的最后面以什么结束。
#比如这样的代码:
delete from t_car where id = 1 or id = 2 or id = 3;
insert into t_car values (null,'1001','凯美瑞',35.0,'2010-10-11','燃油⻋'), (null,'1002','⽐亚迪唐',31.0,'2020-11-11','新能源');
    * 批量删除。foreach标签 : 也可以使用 or 来进行批量删除separator="or"
    int deleteByIds(@Param("ids") Long[] ids);
    
        delete from t_car where id in
        
            #{id}
        
    
    * 批量插入,一次插入多条Car信息
    int insertBatch(@Param("cars") List cars);
    
        insert into t_car values
        
            (null,#{car.carNum},#{car.brand},#{car.guidePrice},#{car.produceTime},#{car.carType})
        
    

7 sql标签与include标签:
sql标签⽤来声明sql⽚段, include标签⽤来将声明的sql⽚段包含到某个sql语句当中
作⽤:代码复⽤。易维护。

    
    
        id, car_num as carNum, brand,  guide_price as guidePrice, produce_time as produceTime, car_type as carType
    

    

你可能感兴趣的:(MyBatis,sql,mybatis,java)