批量插入:
<insert id="batchInsert"> insert into testTable (id,content) values <foreach collection="list" item="item" index="index" separator="," > ( #{item.id}, #{item.content}, ) </foreach> </insert>
Mapper文件中的寫法
<insert id="batchUpdateTjData"> <foreach collection="list" item="item" index="index" open="" close="" separator=";"> UPDATE test_table SET c_a = #{item.ca}, c_b = #{item.cb} WHERE id = #{item.id} </foreach> </insert>
這樣寫總是報錯,調試了很長時間也沒找到問題原因
最后找到這里http://my.oschina.net/jsonavaj/blog/265112 找到了答案
數據庫的鏈接必須加上但是數據庫連接必須加上 allowMultiQueries=true
url="jdbc:mysql://localhost:3306/testDatabase?allowMultiQueries=true" />
http://www.cnblogs.com/modprobe/p/4683274.html
利用MyBatis對數據庫進行DDL(create table,drop table等等)操作
【具體代碼】
1、mapper接口文件內容如下
/** * 執行備份數據庫相關表的Mapper */ public interface BackupDataMapper { /** * 修改數據庫的表名字 * @param originalTableName * @param newTableName * @return */ int alterTableName(@Param("originalTableName") String originalTableName, @Param("newTableName") String newTableName); /** * truncate指定數據庫表的數據 * @param tableName * @return */ int truncateTable(@Param("tableName") String tableName); /** * 根據傳入的表明,創建新的表並且將原表的數據插入到新的Occur表中 * @param newTableName * @param originalTableName */ void createNewTableAndInsertData(@Param("newTableName") String newTableName, @Param("originalTableName") String originalTableName); /** * 統計某張表中的總數據條數。 * @param tableName * @return 指定表中的總記錄條數。 */ int getRecordCount(@Param("tableName") String tableName); /** * 獲得當前數據庫的名字 * @return */ String getCurDataBaseName(); /** * 從指定數據庫中,查詢是否存在某張表 * @param dataBaseName * @param tableName * @return */ String isTargetTableExistInDB(@Param("dataBaseName") String dataBaseName, @Param("tableName") String tableName); }
2、mapper.xml文件內容如下
<mapper namespace="com.dao.BackupDataMapper"> <update id="alterTableName"> alter table ${originalTableName} rename ${newTableName} </update> <update id="truncateTable"> truncate table ${tableName} </update> <update id="createNewTableAndInsertData"> create table ${newTableName} as select * from ${originalTableName} </update> <select id="getRecordCount" resultType="int"> select count(1) from ${tableName} </select> <select id="getCurDataBaseName" resultType="string"> select database(); </select> <select id="isTargetTableExistInDB" resultType="string"> SELECT table_name FROM information_schema.tables WHERE table_schema = #{dataBaseName} and TABLE_NAME = #{tableName} </select> </mapper>
3、注意點
在傳入“表名”作為參數時,一定要使用“${tableName}”的格式,而不能使用“#{tableName}”的格式。因為表名是sql語法要求的一部分,而不是參數
http://www.cnblogs.com/zjrodger/p/5567085.html