天天看点

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

结论:#{}会使用PreparedStatement的参数化查询方式,而${}会直接将参数替换到sql语句中执行(该种方式会有被sql注入的风险)。

测试:

Mapper.xml

<resultMap id="BillList" type="com.demo.bill1.domain.Bill" >
      <result column="TX_TYP" property="txTyp" />
      <result column="REMARK" property="remark" />
      <result column="NO" property="no" />
   </resultMap>
   <!-- ${}方式}-->
   <select id="sfByNo" parameterType="String" resultMap="BillList">
      SELECT * FROM bill  order by ${no}
   </select>
   <!-- #{}方式}-->
   <select id="sfByTxTyp" parameterType="com.demo.bill1.domain.Bill" resultMap="BillList">
      SELECT * FROM bill  where TX_TYP=#{txTyp}
   </select>      

对应的Mapper接口

//使用#{}方式
    List<Bill> sfByTxTyp(Bill bill);
    //使用${}方式时,要想传入一个字符串作为参数,必须加上@Param注解
    List<Bill> sfByNo(@Param("no")String no);      

测试类:

#{}方式:

@Test
    public void sfByTxTyp(){
        Bill bill=new Bill();
        bill.setTxTyp("1");
        billMapper.sfByTxTyp(bill);
    }      

Mybatis日志打印:可以看到是使用参数化查询的方式。

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

${}方式:

@Test
    public void sfByNo(){
        Bill bill=new Bill();
        String no="no";
        System.out.println(billMapper.sfByNo(no));
    }      

Mybatis日志打印:可以看到no作为字符串直接替换到了sql中进行执行。

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

作者:葬瞳飘血

出处:https://www.cnblogs.com/ZTPX/

本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。

继续阅读