mysql foreach insert_MyBatis_动态sql_foreach_mysql下foreach批量插入的两种方式

方法1:

笔记要点

出错分析与总结

工程组织

数据库组织

0.重新修改Bean类    修改

1.定义接口

//批量插入

public void addEmps(@Param("emps")List emps);

2.定义XML映射文件

INSERT INTO tbl_employee(`last_name`,`email`,`gender`,`d_id`)

VALUES(#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})

3.编写测试代码

public SqlSessionFactory getSqlSessionFactory() throwsIOException {

String resource= "mybatis-config.xml";

InputStream inputStream=Resources.getResourceAsStream(resource);return newSqlSessionFactoryBuilder().build(inputStream);

}

@Testpublic void test12() throwsException {

SqlSession openSession=getSqlSessionFactory().openSession();try{

System.out.println("++++++++++---- 2.测试动态SQL: mysql下的foreach的批量插入");

EmployeeMapper_DynamicSQL mapper= openSession.getMapper(EmployeeMapper_DynamicSQL.class);

List emps=new ArrayList<>();

emps.add(new Employee(null,"smith" ,"smith@qq.com" , "1",new Department(1)));

emps.add(new Employee(null,"aliex" ,"aliex@qq.com" , "0",new Department(1)));

mapper.addEmps(emps);

openSession.commit();

}finally{

openSession.close();

}

}

测试结果

++++++++++---- 2.测试动态SQL: mysql下的foreach的批量插入

DEBUG12-05 16:43:52,848 ==> Preparing: INSERT INTO tbl_employee(`last_name`,`email`,`gender`,`d_id`) VALUES (?,?,?,?) , (?,?,?,?) (BaseJdbcLogger.java:145)

DEBUG12-05 16:43:52,873 ==> Parameters: smith(String), smith@qq.com(String), 1(String), 1(Integer), aliex(String), aliex@qq.com(String), 0(String), 1(Integer) (BaseJdbcLogger.java:145)

DEBUG12-05 16:43:52,875 <== Updates: 2 (BaseJdbcLogger.java:145)

方法2:     使用多条mysql语句

1.开启allowMultiQueries=true属性--支持一次查询多条语句, 进入全局配置文件中

a3552045900a137a335046b7211cbf67.png

2.定义XML映射文件

INSERT INTO tbl_employee(last_name,email,gender,d_id)

VALUES (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id});

3.编写测试代码

@Testpublic void test12() throwsException {

SqlSession openSession=getSqlSessionFactory().openSession();try{

System.out.println("++++++++++---- 2-2.测试动态SQL: mysql下的foreach的批量插入");

EmployeeMapper_DynamicSQL mapper= openSession.getMapper(EmployeeMapper_DynamicSQL.class);

List emps=new ArrayList<>();

emps.add(new Employee(null,"smith2" ,"smith@qq.com" , "1",new Department(1)));

emps.add(new Employee(null,"aliex2" ,"aliex@qq.com" , "0",new Department(1)));

mapper.addEmps(emps);

openSession.commit();

}finally{

openSession.close();

}

}

测试结果

idea环境下, 测试失败!原因如下:

++++++++++---- 2-2.测试动态SQL: mysql下的foreach的批量插入

DEBUG12-05 17:14:10,399 ==> Preparing: INSERT INTO tbl_employee(last_name,email,gender,d_id) VALUES (?,?,?,?); ; INSERT INTO tbl_employee(last_name,email,gender,d_id) VALUES (?,?,?,?); (BaseJdbcLogger.java:145)

DEBUG12-05 17:14:10,424 ==> Parameters: smith2(String), smith@qq.com(String), 1(String), 1(Integer), aliex2(String), aliex@qq.com(String), 0(String), 1(Integer) (BaseJdbcLogger.java:145)

org.apache.ibatis.exceptions.PersistenceException:

### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versionfor the right syntax to use near ';

INSERT INTO tbl_employee(last_name,email,gender,d_id)' at line 3

### The error may involve defaultParameterMap

### The error occurredwhilesetting parameters

### SQL: INSERT INTO tbl_employee(last_name,email,gender,d_id) VALUES (?,?,?,?); ; INSERT INTO tbl_employee(last_name,email,gender,d_id) VALUES (?,?,?,?);

### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server versionfor the right syntax to use near ';

INSERT INTO tbl_employee(last_name,email,gender,d_id)' at line 3

........

....

对于MybatisMySQL批量插入和批量更新,可以使用以下方法: 1. 批量插入 使用MyBatisforeach标签,可以很方便地实现批量插入操作。示例如下: ```xml <insert id="batchInsert" parameterType="java.util.List"> insert into my_table (col1, col2, col3) values <foreach collection="list" item="item" separator=","> (#{item.col1}, #{item.col2}, #{item.col3}) </foreach> </insert> ``` 其中,parameterType指定参数类型为List,collection属性指定要插入的List对象,item指定List中的元素,separator指定分隔符。 在Java代码中,调用该方法时,将List对象作为参数传入即可。 2. 批量更新 对于批量更新,可以使用MySQL的replace into语句来实现。示例如下: ```xml <update id="batchUpdate" parameterType="java.util.List"> <foreach collection="list" item="item" separator=";"> replace into my_table (id, col1, col2, col3) values (#{item.id}, #{item.col1}, #{item.col2}, #{item.col3}) </foreach> </update> ``` 其中,replace into语句会先尝试插入记录,如果记录已存在,则更新记录。参数类型和调用方式批量插入相同。 3. 存在即更新 如果只想更新已存在的记录,可以使用MySQL的on duplicate key update语句。示例如下: ```xml <update id="updateIfExists" parameterType="com.example.MyEntity"> insert into my_table (id, col1, col2, col3) values (#{id}, #{col1}, #{col2}, #{col3}) on duplicate key update col1 = values(col1), col2 = values(col2), col3 = values(col3) </update> ``` 其中,id字段为主键。如果该记录已存在,则更新col1、col2、col3字段;否则插入新记录。参数类型为MyEntity,调用方式为传入一个MyEntity对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值