场景
MyBatis 中提供了两种方式将参数赋值到SQL语句中,分别是:#{参数名}和${参数名}
,主要是从实体类对象或则 Map 集合读取内容。
区别
(1)#{参数名} : 采用预编译方式,可以防止 SQL 注入
(2)${参数名}: 采用直接赋值方式,无法阻止 SQL 注入攻击
其实也可以理解为PreparedStatement和Statement的区别:
1.PreparedStatement是预编译的,支持批处理,对于批量处理可以大大提高效率
2.statement每次执行sql语句,相关数据库都要执行sql语句的编译
3.如果只是一次性操作的话,PreparedStatement对象的开销比Statement大,对于一次性操作并不会带来额外的好处。
在大多数情况下,一般都是使用 #{} 读取参数内容。但是在一些特殊的情况下,如:需要在查询语句中动态指定表名,就只能使用 ${} 。再比如:需要动态的指定查询中的排序字段,此时也只能使用 ${},简单来说,在 JDBC 不支持使用占位符的地方,都可以使用 ${}。
直接看一下实现方式,这里我们使用注解的方式实现查询操作:
UserMapper.java:
package com.lks.mapper;
import com.lks.domain.User;
import org.apache.ibatis.annotations.*;
/**
* Created by likaisong on 2019/2/24.
*/
public interface UserMapper {
@Select("select * from ${tableName} where id=#{id}")
User chooseTable(@Param("tableName") String tableName, @Param("id") int id);
}
注意@Param注解参数和sql语句的参数要相同,这里据库表名使用了 ${},查询条件使用了 ${}。
测试类Test Main.java
package com.lks.test;
import com.lks.domain.User;
import com.lks.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.testng.annotations.AfterTest;
import org.testng.annotations.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
/**
* Created by likaisong on 2019/2/24.
*/
public class TestMain {
private static SqlSession session;
private static SqlSession getSqlSession(String resource) {
if (resource == null || "".equals(resource)) {
return null;
}
InputStream inputStream = null;
try {
inputStream = Resources.getResourceAsStream(resource);
} catch (IOException e) {
e.printStackTrace();
}
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
session = sqlSessionFactory.openSession();
return session;
}
@Test
public static void testChooseTable() {
String resource = "mybatis-annotation-config.xml";
session = getSqlSession(resource);
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.chooseTable("users", 1);
System.out.println(user);
}
@AfterTest
public static void closeSession() {
session.close();
}
}
虽然 ${} 的使用是不安全的,但在某些特殊情况下还是要依赖 ${}的。