一、使用#
<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.一般能用#的就别用$.