mybatis怎么实现⼀次插⼊多条数据
前两种为mybatis框架⾥⾯的代码,第三种⽅法为纯java代码时jdbc操作
1.复制原有数据库中的n条记录直接插⼊
<!--复制Menu表中的所有信息复制插⼊,传⼊参数为#{projectid}-->
<insert id="insertMenu" parameterType="int">
INSERT INTO table_menu (projectid,id,fj,level,text,state,type) select #{projectid} as projectid,id,fj,level,text,state,type from table_menu where projectid=0;    </insert>
#{projectid}-->
<insert id="insertMenu" parameterType="int">
INSERT INTO table_menu (projectid,id,fj,level,text,state,type) select #{projectid} as projectid,id,fj,level,text,state,type from table_menu where
projectid=0;
</insert>
2.传⼊参数是放在⼀个list⾥⾯的变量时
<!--将所有信息插⼊PP表⾥⾯,传⼊参数为list,通过<foreach>来遍历list-->
jdbctemplate insert
<insert id="insert_PP" parameterType="java.util.ArrayList">
insert into table_p_p (projectid,propertyid,value) VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.projectid},#{item.propertyid},#{item.value})
</foreach>
</insert>
传⼊参数为list,通过<foreach>来遍历list-->
<insert id="insert_PP" parameterType="java.util.ArrayList">
insert into table_p_p (projectid,propertyid,value) VALUES
<foreach collection="list" item="item" index="index" separator=",">
(#{item.projectid},#{item.propertyid},#{item.value})
</foreach>
</insert>
3.⽤java jdbc代码操作数据库时
每⼀条要执⾏的SQL语句先⽤字符串构造好,之后调⽤batch⽅法
DBConnection db = Instance(); Connection conn = null;
conn = db.getConnection();
if (conn != null) {
// 设置事务为⾮⾃动提交
conn.setAutoCommit(false);
PreparedStatement pstmt = conn.prepareStatement("");
// 添加执⾏sql
String sql="insert into t1(id,name) values(1,'a'),(2,'b'),(3,'c')"; pstmt_funcCall.addBatch(sql);
// 执⾏操作
// 提交事务
connmit();
pstmt.close();
conn.close();
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。