方法一:foreach
容易出現的錯誤:出現SQL語句錯誤
解決方式: 在數據庫的連接url后添加allowMultiQueries=true(允許批量更新)
jdbc.url=jdbc:mysql://localhost:3306/mybatis?allowMultiQueries=true
例子:
xml文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.center.manager.mapper.FundMapper"> <insert id="insertForeach" parameterType="java.util.List" useGeneratedKeys="false"> insert into fund ( id,fund_name,fund_code,date_x,data_y,create_by,create_date,update_by,update_date,remarks,del_flag) <foreach collection="list" item="item" index="index" separator=","> values ( #{item.id}, #{item.fundName},#{item.fundCode},#{item.dateX},#{item.dataY},#{item.createBy}, #{item.createDate},#{item.updateBy},#{item.updateDate},#{item.remarks},#{item.delFlag} ) </foreach> </insert> </mapper>
mapper層
package com.center.manager.mapper; import java.util.List; import org.apache.ibatis.annotations.Mapper; import com.center.manager.entity.Fund; @Mapper public interface FundMapper { int insertForeach(List<Fund> list); }
Fun類
package com.center.manager.entity; import java.util.Date; @data public class Fund { private String id; private String fundName; private String fundCode; private String dateX; private String dataY; private String remarks; private String createBy; private Date createDate; private String updateBy; private Date updateDate; private String delFlag; }
方法二:
Mybatis內置的ExecutorType有3種,默認的是simple,該模式下它為每個語句的執行創建一個新的預處理語句,單條提交sql;而batch模式重復使用已經預處理的語句,
並且批量執行所有更新語句,顯然batch性能將更優;
service層
@Autowired private SqlSessionTemplate sqlSessionTemplate; public void add(List<ApplyInfo> list) { SqlSession sessionn = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH,false); AddInfoDap mapper = session.getMapper(AddInfo.class); for(int i = 0; i < list.seize ; i++) { mapper.addApplicationDetail(lisr.get(i)); if(i == list.size()-1) { session.commit(); session.close(); } } }
xml層
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.center.manager.mapper.FundMapper"> <insert id="addApplicationDetail" parameterType="com.dao.entity.ApplyInfo" > insert into fund ( id,fund_name,fund_code,date_x,data_y,create_by,create_date,update_by,update_date,remarks,del_flag) values ( #{item.id}, #{item.fundName},#{item.fundCode},#{item.dateX},#{item.dataY},#{item.createBy}, #{item.createDate},#{item.updateBy},#{item.updateDate},#{item.remarks},#{item.delFlag} ) </foreach> </insert> </mapper>
mapper層
void addApplicationDetail(ApplyInfo infos)