MyBatis批量插入数据实现(MySQL)
强烈推介IDEA2020.2破解激活,IntelliJ IDEA 注册码,2020.2 IDEA 激活码
先复习一下单条/批量插入数据的sql语句怎么写:
insert into table ([列名],[列名]) values ([列值],[列值]));
或:
insert into table values ([列值],[列值]));
MyBatis批量插入数据到数据库有两种方式:xml文件,注解。
使用批量插入执行的SQL语句应该等价于:
insert into table (id, name,sex,address)
values
(?,?,?,?),(?,?,?,?),(?,?,?,?),(?,?,?,?)
最基础的是用mapping.xml配置的方式,包括以下两种具体方式:
<!-- 在外部for循环调用1000次 -->
<insert id="insert" parameterType="com.xxp.mybatis.Person">
insert into person (id, name,sex,address)
values
(#{id,jdbcType=INTEGER},#{name,jdbcType=VARCHAR},
#{sex,jdbcType=VARCHAR},#{address,jdbcType=VARCHAR})
</insert>
<insert id="insertBatch" >
insert into person ( <include refid="Base_Column_List" /> )
values
<foreach collection="list" item="item" index="index" separator=",">
(null,#{item.name},#{item.sex},#{item.address})
</foreach>
</insert>
参数解释:
foreach的主要作用在构建in条件中,它可以在SQL语句中进行迭代一个集合。foreach元素的属性主要有 collection,item,separator,index,open,close。
mapper接口中的使用:
public interface TabMapper {
public List<Tab> getTabsByConditionLike(@Param("list")List<Integer> ids);
}
注解说明:
MyBatis提供用于插入数据的注解有两个:@insert,@InsertProvider,类似还有:@DeleteProvider@UpdateProvider,和@SelectProvider,
作用:
用来在实体类的Mapper类里注解保存方法的SQL语句
区别:
@Insert是直接配置SQL语句,而@InsertProvider则是通过SQL工厂类及对应的方法生产SQL语句,这种方法的好处在于,我们可以根据不同的需求生产出不同的SQL,适用性更好。
使用:
@Insert
@Insert(“insert into blog(blogId,title,author) values(#blogId,#title,#author)”)
public boolean saveBlog(Blog blog);
@InsertProvider
在mapper接口中的方法上使用@InsertProvider注解:
参数解释:
type为工厂类的类对象,
method为对应的工厂类中的方法,方法中的@Param(“list”)是因为批量插入传入的是一个list,但是Mybatis会将其包装成一个map。其中map的key为“list”,value为传入的list。