mybatis如何在一个update标签中写多条update语句
在mapper里,一个update标签中写了多条update语句,在执行时会抛出sql异常,是因为在mybatis中默认不支持同时执行多条语句。
语句如下:
<update id="updateuserstate">
update sys_user set sys_user_state = #{param2} where sys_user_id = #{param1};
update sys_user set sys_user_state = #{param2} where sys_user_id = #{param1};
update sys_user set sys_user_state = #{param2} where sys_user_id = #{param1};
</update>解决方案
在propertes 或者yml配置文件中找到mysql的jdbc链接,在其后追加&allowmultiqueries=true
例如:
url: jdbc:mysql://127.0.0.1:3306/${db.name}?characterencoding=utf8&usessl=false&zerodatetimebehavior=converttonull&servertimezone=asia/shanghai&allowmultiqueries=truemybatis支持批量update
有的时候我们需要将我们拼接的多条update语句放在mysql一个<update>标签去执行,像平常那样是不行的。
这就需要我们改一些东西了,首先我们需要在我们jdbcurl上拼接上allowmultiqueries=true,如下:
url="jdbc:mysql://localhost:8066/testdb?allowmultiqueries=true"
这个时候我们就可以在我们的<update>标签中写多个update语句了
如果update语句太多的话,比如有个上千条:我们可以在mysql 的my.cnf中配置如下:
wait_timeout=31536000 interactive_timeout=31536000
oracle数据库
<update id="updatebatch" parametertype="java.util.list">
<foreach collection="list" item="item" index="index" open="begin" close="end;" separator=";">
update table_name
<set >
<if test="item.status != null" >
status = #{item.status,jdbctype=integer},
</if>
</set>
where id = #{item.id,jdbctype=bigint}
</foreach>
</update>
mysql数据库
mysql数据库采用一下写法即可执行,但是数据库连接必须配置:&allowmultiqueries=true
例如:
jdbc:mysql://192.168.1.232:3306/test?useunicode=true&characterencoding=utf-8&allowmultiqueries=true
<update id="updatebatch" parametertype="java.util.list">
<foreach collection="list" item="item" index="index" open="" close="" separator=";">
update table_name
<set >
<if test="item.status != null" >
status = #{item.status,jdbctype=integer},
</if>
</set>
where id = #{item.id,jdbctype=bigint}
</foreach>
</update>当然我们页可以在代码中动态拼接如下:
public int batchupdatetfrdata(irequest r, list<long> aetfridlist, string mes, string accountstatus) {
stringbuffer str = new stringbuffer(); for(int i = 0; i < aetfridlist.size(); ++i) {
str.append("update hsae_ae_tfr_events set accounting_status ");
str.append(" = '" + accountstatus + "'");
if (mes != null) {
str.append(", accounting_remarks");
str.append(" = '" + mes + "'");
} str.append(commonutils.whoupdate(r));
str.append(" where tfr_event_id =");
str.append(aetfridlist.get(i));
str.append(";");
}
this.aeeventbatchesmapper.updatesourcedata(str.tostring()); return aetfridlist.size();
}xml:
<update id="updatesourcedata" parametertype="string">
${sqltext}
</update>总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论