public interface CarMapper {
/**
* 根据汽车类型取查询汽车
* @return
*/
List<Car> selectByCarType(String carType);
}
<select id="selectByCarType" resultType="com.powernode.mybatis.pojo.Car">
select
id,
car_num as carNum,
brand,
guide_price as guidePrice,
produce_time as produceTime,
car_type as carType
from t_car
where car_type=#{carType}
select>
@Test
public void testSelectByCarType() throws IOException {
SqlSession session = SqlSessionUtil.openSession();
CarMapper mapper = session.getMapper(CarMapper.class);
List<Car> cars = mapper.selectByCarType("能能源");
cars.forEach(car -> {
System.out.println(car);
});
session.close();
}
#{}:底层使用PreparedStatement。
特点:先进行SQL语句的编译然后给sql语句的?传值。避免SQL注入的风险
${}:底层使用Statement
特点:先进行SQL语句的拼接然后再对SQL语句进行编译。存在SQL注入的风险
优先使用#{} 避免SQL注入的风险
那什么时候使用${}?
举例:跳转到四。
/**
* 查询所有的汽车信息,通过asc升序,desc降序
* @param ascOrDesc
* @return
*/
List<Car> selectAllByAscOrDesc(String ascOrDesc);
<select id="selectAllByAscOrDesc" resultType="com.powernode.mybatis.pojo.Car">
select
id,
car_num as carNum,
brand,
guide_price as guidePrice,
produce_time as produceTime,
car_type as carType
from t_car
order by produce_time #{ascOrDesc}
select>
@Test
public void testSelectByAscOrDesc() throws IOException {
SqlSession session = SqlSessionUtil.openSession();
CarMapper mapper = session.getMapper(CarMapper.class);
List<Car> cars = mapper.selectAllByAscOrDesc("asc");
cars.forEach(car -> {
System.out.println(car);
});
session.close();
}
Preparing: select
id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType
from t_car order by produce_time ?
Parameters: asc(String)
先进行SQL语句的编译在进行传值:
select
id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType
from t_car
order by produce_time 'asc'
查询正常
Preparing: select
id, car_num as carNum, brand, guide_price as guidePrice, produce_time as produceTime, car_type as carType
from t_car order by produce_time asc
Parameters:
如果需要SQL语句的关键字放到SQL语句当中,只能使用${},因为#{}是以值的形式放到SQL语句当中的