我使用的是insert into select mysql查询,但在select语句中,我从Java传递了一个参数(Map)。此查询是使用iBatis框架编写的。查询无法识别select语句中传递的值。
我尝试将#id#
更改为#{id}
、$id$
、#{id}
和${id}
,但没有成功。
查询是这样的:
<insert id="someId" parameterClass="map" >
insert into table1(id, column1, column2)
(
select #id#, A.column1, A.column2
from table2 A left outer join table3 B on A.column = B.column
where <condition>
order by column1, column2
)
</insert>
我已经以13位长id的形式发送了请求参数。在table1模式中,id的数据类型为bigint(20)。
我希望将传递给查询的任何参数(Id)插入到表中。
现在的问题是,它没有认识到#id#
的价值。由于id列约束不为null,因此将抛出"MySQLIntegrityConstraintViolationException: Column 'id' cannot be null" after running the above statement.
为了让它正常工作,我应该尝试什么而不是#id#?或者这可能是其他一些问题?
发布于 2019-05-16 03:37:23
在MyBatis中,#{param}
参数是一个“安全”参数,它只能替换标量值。为了安全起见,它不能用于向您的SQL语句添加任何免费内容,因此您可以忘记SQL注入问题。即使你尝试了你能想到的更糟糕的参数值,你仍然是安全的,你会在晚上睡得很好。
现在,如果您想在SQL中插入任意内容(以生成某种动态SQL),并冒着夜不能耐的风险, MyBatis为您提供了${param}
参数(您是否发现了其中的区别?)。这些字符串参数直接插入到SQL语句中。使用此策略,您的查询应该如下所示:
<insert id="someId" parameterClass="map" >
insert into table1(id, column1, column2)
(
select ${id}, A.column1, A.column2
from table2 A left outer join table3 B on A.column = B.column
where <condition>
order by column1, column2
)
</insert>
现在,请注意,如果管理不当,此策略很容易受到SQL注入的攻击。确保id
参数的值来自应用程序内部,而不是从网页或其他外部用户界面或应用程序检索。
https://stackoverflow.com/questions/56154637
复制相似问题