mybatis系列之#{} 和 ${} 区别

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31156277/article/details/80951534

一、#{} 和 ${} 区别

参数设置不同的格式,然后根据打印日志进行区别

1.1 使用#{} 、${} 查看打印日志

<select id="getStudentByIdAndName" resultType="com.study.entity.Student">
   select * from tb_student where id = ${id} and name = #{name}
</select>
@Test
 public void testGetStudentByIdAndName() throws Exception {
     try(SqlSession session = getSqlSession()) {
         StudentMapper mapper = session.getMapper(StudentMapper.class);
         Student student = mapper.getStudentByIdAndName(1,"小米");
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

打印日志

DEBUG 07-07 15:48:26,522 ==>  Preparing: select * from tb_student where id = 1 and name = ?   (BaseJdbcLogger.java:145) 
DEBUG 07-07 15:48:26,660 ==> Parameters: 小米(String)  (BaseJdbcLogger.java:145) 
DEBUG 07-07 15:48:26,743 <==      Total: 1  (BaseJdbcLogger.java:145) 

1.2 结果分析

select * from tb_student where id = 1 and name = ? 

#{}:是以预编译的形式,将参数设置到sql语句中;像PreparedStatement 处理机制,使用占位符;能够防止sql注入
${}:取出的值直接拼装在sql语句中;会有安全问题;

大多情况下,我们去参数的值都应该去使用#{};

不过 ${} 也有其独特的使用之处:
原生jdbc不支持占位符的地方我们就可以使用${}进行取值

应用场景:比如分表、排序……;这是使用#{} 做不到的。

select * from ${year}_salary where xxx; --分表
select * from tbl_employee order by ${f_name} ${order} ; --排序校验等

二、#{ }更多的用法

使用#{} 可以指定参数值的类型,比如下面这些类型:

#{property,javaType=int,jdbcType=NUMERIC}

javaType、 jdbcType、 mode(存储过程)、 numericScale、resultMap、 typeHandler、 jdbcTypeName、 expression(未来准备支持的功能)


案例

有些数据库可能不能识别mybatisnull的默认处理。比如Oracle(报错)JdbcType OTHER:无效的类型;因为mybatis对所有的null都映射的是原生JdbcOTHER类型,oracle不能正确处理;


解决方案:

  • #{ }中指定类型
  • 全局设置 <setting/>

猜你喜欢

转载自blog.csdn.net/qq_31156277/article/details/80951534