mybatis中的#{}和${}的区别

#{}:底层使用PreparedStatement。
特点:先进行SQL语句的编译,然后给SQL语句中的占位符?传值。
${}:底层使用Statement.
特点:先进行SQL语句的拼接,然后在对SQL语句进行编译。

【注意】:优先使用#{},这是原则,避免SQL注入的风险。

【什么时候用${}】:传入Mapper的语句不需要带  '  '  的时候使用,如果需要SQL语句的关键字放到SQL语句中,只能使用${},因为#{}是以值的形式放到SQL语句当中的。

批量删除-CarMapper语句:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.CarMapper">
    <delete id="deleteBatch">
        delete from t_car where id in(${ids})
    </delete>
</mapper>

测试程序:

 @Test
    public void testDeleteBatch(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        int i = mapper.deleteBatch("13,19,21");
        System.out.println(i);
    }

输出结果:3

模糊查询-CarMapper:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.CarMapper">
    <select id="selectByBrandLike">
        select
           car_num as carNum,
           brand,
           guide_price as guidePrice,
           produce_time as produceTime,
           car_type as carType
        from
           t_car
        where
           <!--brand like '%${brand}%'-->                <!--第一种方式-->
           brand like concat('%',#{brand},'%')            <!--第二种方式-->
           brand like concat('%','${brand}','%')            <!--第三种方式-->
           "%"#{brand}"%"                                  <!--第四种方式-->
    </select>
<mapper>

测试样例:

 @Test
    public void testSelectByBrandLike(){
        SqlSession sqlSession = SqlSessionUtil.openSession();
        CarMapper mapper = sqlSession.getMapper(CarMapper.class);
        List<Car> cars = mapper.selectByBrandLike("东风");
        cars.forEach(car -> System.out.println(car));
    }

相关推荐

  1. Mybatis${}#{}区别

    2024-01-24 21:12:03       23 阅读
  2. mybatis #{} ${}区别是什么?

    2024-01-24 21:12:03       12 阅读
  3. mybatis$#区别以及各自使用场景

    2024-01-24 21:12:03       18 阅读
  4. mybatismybatis-plus区别

    2024-01-24 21:12:03       14 阅读
  5. Mybatis-pluswrapper区别

    2024-01-24 21:12:03       34 阅读
  6. mybatis - 取值符号:# $区别

    2024-01-24 21:12:03       15 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-24 21:12:03       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-24 21:12:03       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-24 21:12:03       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-24 21:12:03       18 阅读

热门阅读

  1. qt学习:json数据文件读取写入

    2024-01-24 21:12:03       35 阅读
  2. 学习python仅收藏此一篇就够了(闭包,装饰器)

    2024-01-24 21:12:03       36 阅读
  3. nii文件的裁剪

    2024-01-24 21:12:03       33 阅读
  4. c++动态调用dll

    2024-01-24 21:12:03       40 阅读
  5. 输入输出 xtu oj 1603

    2024-01-24 21:12:03       34 阅读