mybatis学习三之模糊查询的几种使用方法

本文详细解析了MyBatis中#与$符号的使用区别,包括SQL注入防护、动态SQL生成及参数传递等内容,对于理解MyBatis动态SQL机制具有重要指导意义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、使用#

 <select id="selectByTitle" resultType="Blog" resultMap="blogResultMap">
        select * from Blog where title like "%"#{title}"%"
   </select>

添加接口:

Blog selectByTitle(String title);

添加测试用例:

    @Test
    public void testSelectByTitle() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = mapper.selectByTitle("ful");
        sqlSession.close();
        logger.info("blog is:{}", blog);
    }

运行结果:

 发现#是一个占位符。

注意,%要使用双引号,  因为使用#时,mybatis会自动加单引号。

二、使用$

添加mapper映射:

<select id="selectByTitle1" resultType="Blog" resultMap="blogResultMap">
        select * from Blog where title like '%${title}%'
    </select>

 添加接口:

Blog selectByTitle1(String title);

添加测试用例:

    @Test
    public void testSelectByTitle1() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = mapper.selectByTitle1("ful");
        sqlSession.close();
        logger.info("blog is:{}", blog);
    }

 运行结果:

 使用$时,并不是占位符

注意:需要在$外面加单引号,mybatis是不会自动加的。

三、使用CONCAT()函数

添加mapper映射:

    <select id="selectByTitleWithConcat" resultType="Blog" resultMap="blogResultMap">
        select * from Blog where title like  CONCAT('%', #{title}, '%')
    </select>

添加接口:

Blog selectByTitleWithConcat(String title);

添加测试用例:

    @Test
    public void selectByTitleWithConcat() {
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        Blog blog = mapper.selectByTitleWithConcat("ful");
        sqlSession.close();
        logger.info("blog is:{}", blog);
    }

 运行结果:

#与$的区别:

1. $将传入的数据直接显示生成在sql中。
  
2. #方式能够很大程度防止sql注入。
  
3.$方式无法防止Sql注入。

4.$方式一般用于传入数据库对象,例如传入表名.
  
5.一般能用#的就别用$.

MyBatis排序时使用order by 动态参数时需要注意,用$而不是#

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值