mybatis ${}与#{}的区别mybatis三种传值方式

简单来讲#{} 解析的是占位符?能够防止SQL注入, 好比打印出来的语句 select * from table where id=?
然而${} 则是不能防止SQL注入打印出来的语句 
select * from table where id=2  实实在在的参数

第一种方案 

DAO层的函数方法 sql

[sql] view plain copyapp

  1. Public User selectUser(String name,String area);  

对应的Mapper.xml  函数

[sql] view plain copyui

  1. <select id="selectUser" resultMap="BaseResultMap">  
  2.     select  *  from user_user_t   where user_name = #{0} and user_area=#{1}  
  3. </select>  

其中,#{0}表明接收的是dao层中的第一个参数,#{1}表明dao层中第二参数,更多参数一致日后加便可。spa

第二种方案

此方法采用Map传多参数..net

Dao层的函数方法xml

[sql] view plain copyblog

  1. Public User selectUser(Map paramMap);  

对应的Mapper.xml接口

[sql] view plain copyip

  1. <select id=" selectUser" resultMap="BaseResultMap">  
  2.    select  *  from user_user_t   where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}  
  3. </select>  

Service层调用

[sql] view plain copy

  1. Private User xxxSelectUser(){  
  2. Map paramMap=new hashMap();  
  3. paramMap.put(“userName”,”对应具体的参数值”);  
  4. paramMap.put(“userArea”,”对应具体的参数值”);  
  5. User user=xxx. selectUser(paramMap);}  

我的认为此方法不够直观,见到接口方法不能直接的知道要传的参数是什么。

第三种方案

Dao层的函数方法

[sql] view plain copy

  1. Public User selectUser(@param(“userName”)Stringname,@param(“userArea”)String area);  

对应的Mapper.xml

[sql] view plain copy

  1. <select id=" selectUser" resultMap="BaseResultMap">  
  2.    select  *  from user_user_t   where user_name = #{userName,jdbcType=VARCHAR} and user_area=#{userArea,jdbcType=VARCHAR}  
  3. </select>   

我的以为这种方法比较好,能让开发者看到dao层方法就知道该传什么样的参数,比较直观,我的推荐用此种方案。

相关文章
相关标签/搜索