Mybatis使用批量插入MySQL数据
Mysql的insert语句:
# 方式一:
insert into 表名(列名,...) values(值1,...);
# 方式二:
insert into 表名
set 列名=值,列名=值,...
# 批量
INSERT INTO beauty
VALUES(23,'小白1','女','1990-4-23','1898888888',NULL,2)
,(24,'小白2','女','1990-4-23','1898888888',NULL,2)
,(25,'小白3','女','1990-4-23','1898888888',NULL,2);
# 子查询插入
INSERT INTO beauty(id,NAME,phone)
SELECT id,boyname,'1234567'
FROM boys WHERE id<3;
mybatis:foreach
<!--public List<Employee> getEmpsByConditionForeach(List<Integer> ids); -->
<select id="getEmpsByConditionForeach" resultType="cn.codewhite.pojo.Employee">
select * from tbl_employee
<!--
要求:获取员工,根据集合遍历的id 原sql语句:select * from tbl_employee where id in(1,2,3)
collection:指定要遍历的集合:这里遍历:ids,需要注解!
list类型的参数会特殊处理封装在map中,map的key就叫list
item:将当前遍历出的元素赋值给指定的变量
separator:每个元素之间的分隔符,如果不写这个的话,在#{变量名}后边加“,”那么会报错。
open:遍历出所有结果拼接一个开始的字符
close:遍历出所有结果拼接一个结束的字符
index:索引。遍历list的时候是index就是索引,item就是当前值
遍历map的时候index表示的就是map的key,item就是map的值
#{变量名}就能取出变量的值也就是当前遍历出的元素
-->
<foreach collection="ids" item="item_id" separator=","
open="where id in(" close=")">
#{item_id}
</foreach>
</select>
Mybatis:批量插入环境搭建:
SysLog实体类:
/**
* 系统日志表
* @create 2020-07-02 22:35
*/
@Data
public class SysLog {
/**
* 编号
*/
private String id;
/**
* 操作模块
*/
private String title;
/**
* 访问方法
*/
private String method;
/**
* 请求方式
*/
private String requestType;
/**
* 操作用户
*/
private String username;
/**
* 请求的url
*/
private String url;
/**
* 主机IP
*/
private String ip;
/**
* 执行时长
*/
private Long useTime;
/**
* 业务类型(0其它 1新增 2修改 3删除)
*/
private Integer businessType;
/**
* 返回参数
*/
private String returnArgs;
/**
* 操作时间
*/
private Date operatingTime;
SysLogMapper:
/**
* 系统操作日志mapper
* @create 2020-08-24 20:59
*/
public interface SysLogMapper {
/**
* 插入多条日志
*/
int insertLogs(@Param("sysLogs") List<SysLog> sysLogs) throws Exception;
}
SysLogMapper.xml:
<!--批量插入-->
<insert id="insertLogs" parameterType="list">
insert into sys_log(
id,username,operatingTime,useTime,ip,url,method,requestType,title,businessType,returnArgs
)
VALUES
<foreach collection="sysLogs" item="sysLog" index="index" separator=",">
(
#{sysLog.id},
#{sysLog.username},
#{sysLog.operatingTime},
#{sysLog.useTime},
#{sysLog.ip},
#{sysLog.url},
#{sysLog.method},
#{sysLog.requestType},
#{sysLog.title},
#{sysLog.businessType},
#{sysLog.returnArgs}
)
</foreach>
</insert>