mybatis中#和$符号的区别

#{ }

  1.在使用#{}时意味着用的是预编译,sql语句会用?占位,传的值会用 ' ' 包住,可防止sql注入 

select * from student where id=#{id}

  编译后是

select * from student where id='1'

 

${ }

   1.在使用${}时传的值会原样输入

select * from ${tableName} order by ${id}

  则后台语句为:select * from student order by id
  使用#{}则成:select * from 'student' order by 'id'是不对的

注:

  在使用以下的配置时,必须使用#{}

  

<select id="selectMessageByIdI" parameterType="int" resultType="Message">
          select * from message where id=#{id};
</select>
parameterType="int"已声明了参数类型是int所有用#{id}

还有在键表时也要用${表名},用#{表名}就会报错,因为在编译时用#{表名}会在表名加上“”号如“表名”,执行时就会报sql语句错误
<update id="addTable" parameterType="com.example.yunpingtai.domain.BuildTable">
         CREATE TABLE ${tableName} (id bigint(20) NOT NULL AUTO_INCREMENT,PRIMARY KEY (id)) 
</update>

  

原文地址:https://www.cnblogs.com/bigbigxiao/p/11946575.html