#{}:底层使用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文章来源:https://www.toymoban.com/news/detail-822093.html
文章来源地址https://www.toymoban.com/news/detail-822093.html
模糊查询-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));
}
到了这里,关于mybatis中的#{}和${}的区别的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!