1. 程式人生 > >mybatis中$和#的區別

mybatis中$和#的區別

在mybatsi中, ${}會直接取值為string,直接寫在SQL中。 #{}會表現為在SQL中一個佔位符,然後取引數對應的值進行填充SQL

${}在動態解析的時候,會將我們傳入的引數當做String字串填充到我們的語句中,就會變成下面的語句

1.使用${}取值。會直接拼接到SQL中,而不會作為佔位符

		<!-- foreach實現動態update
		
		這一節主要介紹當引數型別是 Map 時, foreach 如何實現動態 UPDATE 。
當引數是 Map 型別的時候, foreach 標籤的工 ndex 屬性值對應的不是索引值,而是 Map
中的 key,利用這個 key 可以實現動態 UPDATE 。
現在需要通過指定的列名和對應的值去更新資料
		 -->
		<update id="updateByMap">
			update sys_user
			set
		<foreach collection="_parameter" item="val" index = "key" separator=",">
			${key} = #{val}
		</foreach>
		where
		id = #{id}
	</update>

輸出的SQL語句為:

==>  Preparing: update sys_user set user_name = ? , id = ? where id = ? 
==> Parameters: 1222(String), 1(Long), 1(Long)

使用#取值,這樣就會報錯。因為set 後面應該都是列名稱,不應該帶’’


		<update id="updateByMap">
			update sys_user
			set
		<foreach collection="_parameter" item="val" index = "key" separator=",">
			#{key} = #{val}
		</foreach>
		where
		id = #{id}
	</update>
==>  Preparing: update sys_user set ? = ? , ? = ? where id = ? 
==> Parameters: user_name(String), 1222(String), id(String), 1(Long), 1(Long)
==>  Preparing: update sys_user set ? = ? , ? = ? where id = ? 
==> Parameters: user_name(String), 1222(String), id(String), 1(Long), 1(Long)
org.apache.ibatis.exceptions.PersistenceException: 
### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''user_name' = '1222'
		 , 
			'id' = 1
		 
		where
		id = 1' at line 4