码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis中#{}和${}的区别

时间:2019-11-04 19:17:06      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:evo   16px   ESS   defaults   mys   控制台   参数   tran   man   

在MyBatis 的映射配置文件中,动态传递参数有两种方式

  1. #{} 占位符 可以获取map中的值或者pojo对象属性的值;
  2. ${} 拼接符 可以获取map中的值或者pojo对象属性的值;

两者的作用都是从传入的pojo中获取对象属性的值

#{} 和 ${} 的区别

#{} 为参数占位符 ? 防止sql注入

例如

<select id="getRoleById" resultType="com.esummer.vo.RoleVo">
  <!-- 使用#{}获取参数 --> select * from tb_role where tb_role.role_id=#{roleId} </select>

单元测试方法

@Test
public void testDemo(){
     RoleVo roleById = roleMapper.getRoleById(1);
     System.out.println(roleById);
}

控制台输出内容

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f213a2] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.jdbc.JDBC4Connection@6094de13] will not be managed by Spring
==>  Preparing: select * from tb_role where tb_role.role_id=? 
==> Parameters: 1(Integer) 
<==    Columns: role_id, role_name
<==        Row: 1, admin
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4f213a2]

可看出 #{} 是通过以预编译的形式将参数设置到sql语句中 mybatis底层再返回PreparedStatement对象

${} 为字符串替换,即 sql 拼接

<select id="getRoleById" resultType="com.esummer.vo.RoleVo">
  <!-- 使用${}获取参数 --> select * from tb_role where tb_role.role_id=${roleId} </select>

单元测试方法

@Test
public void testDemo(){
     RoleVo roleById = roleMapper.getRoleById(1);
     System.out.println(roleById);
}

控制台输出内容

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@370c7cc5] was not registered for synchronization because synchronization is not active
JDBC Connection [com.mysql.jdbc.JDBC4Connection@38159384] will not be managed by Spring
==>  Preparing: select * from tb_role where tb_role.role_id=1 
==> Parameters: 
<==    Columns: role_id, role_name
<==        Row: 1, admin
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@370c7cc5]

可看出 ${} 是在获得传入的参数后 将参数通过字符串方式 与sql语句进行拼接

 #{} 和 ${} 的作用

  1. #{} 能防止sql 注入
  2. ${} 不能防止sql 注入

 

Mybatis中#{}和${}的区别

标签:evo   16px   ESS   defaults   mys   控制台   参数   tran   man   

原文地址:https://www.cnblogs.com/Esummer/p/11793807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!