MyBatis-动态SQL

实体类Car:

package com.bjpowernode.domain;

public class Car {

    private Integer id;

    private String carNum;

    private String brand;

    private Double guidePrice;

    private String produceTime;

    private String carType;

    //构造方法略

    //setter and getter 略

    //toString略

数据库中的t_car表:

在MyBatis核心配置文件中开启驼峰命名自动映射

<settings>

       <setting name="mapUnderscoreToCamelCase" value="true"/>

</settings>

开启多条件查询:(查询条件有可能是:0、1、2、3...条)

if标签:

持久层接口中

/**

 * 根据多条件查询Car

 * @param brand

 * @param guidePrice

 * @param carType

 * @return

 */

 List<Car> selectByIf(@Param("brand") String brand, @Param("guidePrice") Double guidePrice,

   @Param("carType") String carType);

sql映射文件中

<select id="selectByIf" resultType="car">

        select * from t_car where 1=1

        //下行代码中test属性值里的brand源自持久层接口中方法里形参前面@Param()设定的值

        <if test="brand != null and brand != ''">

        //下行代码中like前面的brand源自数据库表中的字段名,#{}里面的brand与上行代码中的brand相同

                 and brand like #{brand}"%"

        </if>

        <if test="guidePrice != null and guidePrice != ''">

                 and guide_price >= #{guidePrice}

        </if>

        <if test="carType != null and carType != ''">

                 and car_type = #{carType}

        </if>

 </select>

使用if标签需要注意以下几点:

        1、if标签中test属性是必须的,其属性值为布尔类型false或true  

  true表示if标签中的sql语句会自动拼接;false表示if标签中的sql语句不会拼接

        2、test属性值中的写法:

                1)如果持久层接口中方法里的形参使用了@Param注解,那么test中写的是@Param注解指定的参数名。上面例子中就是这种情况。

                2)如果没有使用@Param注解,那么test中要出现的是:param1、param2...或 arg0、arg1…

                3)如果持久层接口中方法里的形参使用了POJO,那么test中出现的是POJO类的属性名。

        3、主sql中where关键字后面为什么写了1=1这个表达式?

                回答:当所有的if标签里test的属性值都是false时,如果没有这个恒成立的表达式,关键字where后面就没有内容了,这就是一条非法的sql语句了,有了这个恒成立的条件,就不会出现非法sql语句的情况。

        4、在mybatis的动态SQL当中,不能使用'&&',只能使用'and'。

where标签:

where标签的作用:

1、让where子句更加动态智能。使用where标签后主sql语句中不再需要像0=0这样恒成立的条件

2、所有条件都为空时,where标签保证不会生成where子句。

3、自动去除某些条件前面多余的and或or。后面的多余条件不能去除。

持久层接口中

/**

* 根据多条件查询Car,使⽤where标签

* @param brand

* @param guidePrice

* @param carType

* @return

*/

List<Car> selectByWhere(@Param("brand") String brand, @Param("guidePrice") DoubleguidePrice,

@Param("carType") String carType);

 

sql映射文件中

<select id="selectByWhere" resultType="car">

         select * from t_car

         <where>

                  <if test="brand != null and brand != ''">

                           and brand like #{brand}"%"

                  </if>

                  <if test="guidePrice != null and guidePrice != ''">

                           and guide_price >= #{guidePrice}

                  </if>

                  <if test="carType != null and carType != ''">

                           and car_type = #{carType}

                  </if>

          </where>

</select>

trim标签

        trim标签的属性:

                prefix:在trim标签中的语句前添加内容

                suffix:在trim标签中的语句后添加内容

                prefixOverrides:前缀覆盖掉(去掉)

                suffixOverrides:后缀覆盖掉(去掉)

 

持久层接口中

/**

* 根据多条件查询Car,使⽤trim标签

* @param brand

* @param guidePrice

* @param carType

* @return

*/

List<Car> selectByTrim(@Param("brand") String brand, @Param("guidePrice") Double guidePrice,

      @Param("carType") String carType);

sql映射文件中

<select id="selectByTrim" resultType="car">

        select * from t_car

        <trim prefix="where" suffixOverrides="and|or">

                   //下行代码中的test属性值中的brand源自持久层接口中方法里@Param()设定的值

                   <if test="brand != null and brand != ''">

                           //下行代码中的第一个brand源自数据库表中的字段名,#{}里面的brand与上行代码中的brand相同

                            brand like #{brand}"%" and

                   </if>

                   <if test="guidePrice != null and guidePrice != ''">

                            guide_price <= #{guidePrice} and

                   </if>

                   <if test="carType != null and carType != ''">

                            car_type = #{carType}

                   </if>

           </trim>

</select>

set标签

主要使用在update语句当中,用来生成set关键字,同时去掉最后多余的“,”

比如我们只更新提交的不为空的字段,如果提交的数据是空或者"",那么这个字段我们将不更新。

持久层接口中

/**

* 更新信息,使⽤set标签

* @param car

* @return

*/

int updateBySet(Car car);

sql映射文件中

<update id="updateWithSet">

        update t_car

        <set>

                 //下行代码中test属性值里面的carNum源自实体类Car的属性名

                 <if test="carNum != null and carNum != ''">

                 //下行代码中的car_num是数据库表中的字段名,花括号中的carNum是实体类Car的属性名

                          car_num = #{carNum},

                 </if>

                 <if test="brand != null and brand != ''">

     brand = #{brand},

   </if>

                 <if test="guidePrice != null and guidePrice != ''">

                      guide_price = #{guidePrice},

                 </if>

                 <if test="produceTime != null and produceTime != ''">

                      produce_time = #{produceTime},

                 </if>

                 <if test="carType != null and carType != ''">

                      car_type = #{carType},

                </if>

       </set>

       where id = #{id}

</update>

 

choose when otherwise 标签

这三个标签是在一起使用,其语法格式是:(只有一个分支被执行

<choose>

      <when></when>

      <when></when>

      <when></when>

      <otherwise></otherwise>

</choose>

这三个标签的使用相当于:

if(){

}else if(){

}else if(){

}else if(){

}else{

}

持久层接口中

/**

* 使用choose when otherwise标签查询

* @param brand

* @param guidePrice

* @param produceTime

* @return

*/

List<Car> selectByChoose(@Param("brand") String brand, @Param("guidePrice") Double guidePrice,

                                                       @Param("produceTime") String produceTime);

sql映射文件中

<select id="selectWithChoose" resultType="car">

        select * from t_car

        <where>

               <choose>

                     //下行代码中test的属性值中的brand源自持久层接口中方法里形参前面@Param中设定的值

                      <when test="brand != null and brand != ''">

                            //下行代码中第一个brand源自数据库表中的字段名,花括号中的brand源自持久层接口中方法里的形参名

                             brand like #{brand}"%"

                      </when>

                      <when test="guidePrice != null and guidePrice != ''">

                             guide_price >= #{guidePrice}

                      </when>

                      <otherwise>

                               produce_time >= #{produceTime}

                      </otherwise>

             </choose>

     </where>

</select>

 

foreach标签

循环数组或集合,动态生成sql,比如这样的SQL:

批量删除:

delete from t_car where id in(1,2,3);

delete from t_car where id = 1 or id = 2 or id = 3;

1)使用含有'in'的sql语句进行删除

在持久层接口中

/**

* 通过foreach完成批量删除

* @param ids

* @return

*/

int deleteBatchByForeach(@Param("ids") Long[] ids);

 

在映射文件中

<!--

collection:集合或数组

item:集合或数组中的元素

separator:集合或数组中元素的分隔符

open:foreach标签中所有内容的开始

close:foreach标签中所有内容的结束

-->

<delete id="deleteByForeach">

          delete from t_car where id in   

          //下行代码中的collection的属性值源自持久层接口中方法的形参之前的@Param中设定的值

          <foreach collection="ids" item="id" separator="," open="(" close=")">

                   //下行代码中花括号里面的id源自上行代码中item的属性值

                   #{id}

          </foreach>

</delete>

 

测试代码

@Test

public void testDeleteByForeach(){

        SqlSession sqlSession = SqlSessionUtil.openSession();

        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);

        int count = mapper.deleteByForeach(new Long[]{40L, 41L, 42L});

        System.out.println("删除记录条数是:" + count);

        sqlSession.commit();

        sqlSession.close();

}

 

2)使用含有'or'的sql语句进行删除

在持久层接口中

/**

* 通过foreach完成批量删除

* @param ids

* @return

*/

int deleteByForeach2(@Param("ids") Long[] ids);

 

在映射文件中

<delete id="deleteByForeach2">

         delete from t_car where  

         //下行代码中的collection的属性值源自持久层接口中方法的形参之前的@Param中设定的值

         <foreach collection="ids" item="id" separator="or">

                  //下行代码中花括号里面的id源自上行代码中item的属性值

                  id = #{id}

         </foreach>

</delete>

 

测试代码

@Test

public void testDeleteByForeach2(){

SqlSession sqlSession = SqlSessionUtil.openSession();

    CarMapper mapper = sqlSession.getMapper(CarMapper.class);

    Long[] ids = {158L,159L,160L};

    int count = mapper.deleteByForeach2(ids);

    System.out.println(count);

    sqlSession.commit();

    sqlSession.close();

}

批量添加

在持久层接口中

/**

* 批量添加,使⽤foreach标签

* @param cars

* @return

*/

int insertByForeach(@Param("cars") List<Car> cars);

在映射文件中

<insert id="insertByForeach">

        insert into t_car values

        //下行代码中的collection的属性值源自持久层接口中方法的形参之前的@Param中设定的值

        <foreach collection="cars" item="car" separator=",">

               //下行代码中的car源自上行代码中item的值

                (null,#{car.carNum},#{car.brand},#{car.guidePrice},#{car.produceTime},#{car.carType})

        </foreach>

</insert>

测试代码

@Test

public void testInsertByForeach(){      

SqlSession sqlSession = SqlSessionUtil.openSession();

    CarMapper mapper = sqlSession.getMapper(CarMapper.class);

    Car car1 = new Car(null,"1200", "比亚迪秦", 30.0, "2021-11-23", "新能源");

    Car car2 = new Car(null,"1201", "比亚迪宋", 33.0, "2022-10-11", "新能源");

    Car car3 = new Car(null,"1202", "比亚迪汉", 35.0, "2023-06-22", "新能源");

    List<Car> cars = new ArrayList<>();

    cars.add(car1);

    cars.add(car2);

    cars.add(car3);

    mapper.insertBatch(cars);

    sqlSession.commit();

    sqlSession.close();

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值