Mybatis需要注意的细节,
分享于 点击 15842 次 点评:166
Mybatis需要注意的细节,
mybatis第二篇
1.${}和#{}的区别
- 1.#在传参的时候,会自动拼接单引号;$不能拼接单引号;
2.$传参时,一般不支持jdbcType指定类型的写法;#则可以;如:
#{name,jdbcType=VARCHAR}
3.$一般用于在sql中拼接表名,结果排序,模糊查询等操作;其他正常参数传递一般使用
4.因为${}使用后不会自动拼接单引号,所以可能还会导致sql攻击
select * from user where username=${username} and password=${username}
当输入值为" ‘ttt' or '22'='22' ”时,sql就被替换为
select * from user where username='ttt' or '22'='22' and password='ttt' or '22'='22'
2.在插入数据时获取主键
<!-- 增加 -->
<insert id="insert" parameterType="cn.sz.gl.pojo.Users" >
insert into users(id,name,password)
values(users_seq.nextval, #{name,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR})
</insert>
2.$传参时,一般不支持jdbcType指定类型的写法;#则可以;如:
#{name,jdbcType=VARCHAR}
3.$一般用于在sql中拼接表名,结果排序,模糊查询等操作;其他正常参数传递一般使用
4.因为${}使用后不会自动拼接单引号,所以可能还会导致sql攻击
select * from user where username=${username} and password=${username}
当输入值为" ‘ttt' or '22'='22' ”时,sql就被替换为
select * from user where username='ttt' or '22'='22' and password='ttt' or '22'='22'
<!-- 增加 -->
<insert id="insert" parameterType="cn.sz.gl.pojo.Users" >
insert into users(id,name,password)
values(users_seq.nextval, #{name,jdbcType=VARCHAR},
#{password,jdbcType=VARCHAR})
</insert>
这里提供两种方案
3.ThreadLocal本地线程的使用
现编写工具类MySqlSessionFactory.java
public class MySqlSessionFactory {
private static final String RESOURCE = "mybatis_config.xml";
private static SqlSessionFactoryBuilder builder = null;
private static SqlSessionFactory factory = null;
private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
static{
try {
InputStream is = Resources.getResourceAsStream(RESOURCE);
builder = new SqlSessionFactoryBuilder();
factory = builder.build(is);
} catch (IOException e) {
System.out.println("加载配置文件.....");
}
}
public static SqlSession getMySqlSession() {
SqlSession sqlSession = threadLocal.get();
if(sqlSession==null) {
sqlSession = factory.openSession();
threadLocal.set(sqlSession);
}
return sqlSession;
}
public static void closeSqlSession() {
SqlSession sqlSession = threadLocal.get();
if(sqlSession!=null) {
sqlSession.close();
}
threadLocal.set(null);
}
}
使用在service中
public class UsersServiceImpl implements UsersService {
private static SqlSession sqlsession
=MySqlSessionFactory.getMySqlSession();
private UsersDao dao = null;
/**
* 查询全部
* @return
*/
public List<Users> findAll(){
try {
dao=sqlsession.getMapper(UsersDao.class);
return dao.findAll();
} catch (Exception e) {
System.out.println("findAll'查询列表失败!");
}
return Collections.EMPTY_LIST;
}
}
测试
public class UsersServiceImplTest {
private UsersService service=null;
@Before
public void init() {
service=new UsersServiceImpl();
}
@Test
public void testFindAll() {
service.findAll().forEach(System.out::println);
}
}
相关文章
- 暂无相关文章
用户点评