【注意】:优先使用#{},这是原则,避免SQL注入的风险。
【什么时候用${}】:传入Mapper的语句不需要带? '? '? 的时候使用,如果需要SQL语句的关键字放到SQL语句中,只能使用${},因为#{}是以值的形式放到SQL语句当中的。
<?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
<?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));
}