oracle 整合 mybatis 批量插入数据
时间: 2023-11-09 21:10:15 浏览: 105
MyBatis批量插入数据到Oracle数据库中的两种方式(实例代码)
要使用Oracle和Mybatis进行批量插入数据,可以使用以下步骤:
1. 配置Mybatis的批处理功能。在Mybatis的配置文件中,添加以下配置:
```
<settings>
<setting name="jdbcTypeForNull" value="NULL" />
<setting name="cacheEnabled" value="true" />
<setting name="lazyLoadingEnabled" value="false" />
<setting name="aggressiveLazyLoading" value="false" />
<setting name="multipleResultSetsEnabled" value="true" />
<setting name="useColumnLabel" value="true" />
<setting name="useGeneratedKeys" value="false" />
<setting name="autoMappingBehavior" value="PARTIAL" />
<setting name="defaultExecutorType" value="SIMPLE" />
<setting name="defaultStatementTimeout" value="25" />
<setting name="safeRowBoundsEnabled" value="false" />
<setting name="mapUnderscoreToCamelCase" value="false" />
<setting name="localCacheScope" value="SESSION" />
<setting name="jdbcTypeForNull" value="NULL" />
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString" />
<setting name="defaultScriptingLanguage" value="org.apache.ibatis.scripting.xmltags.XMLLanguageDriver" />
<setting name="callSettersOnNulls" value="false" />
<setting name="logImpl" value="STDOUT_LOGGING" />
<setting name="configurationFactory" value="org.apache.ibatis.session.ConfigurationFactory" />
<setting name="defaultEnumTypeHandler" value="org.apache.ibatis.type.EnumOrdinalTypeHandler" />
<setting name="defaultObjectFactory" value="org.apache.ibatis.reflection.factory.DefaultObjectFactory" />
<setting name="defaultObjectWrapperFactory" value="org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory" />
<setting name="useActualParamName" value="true" />
<setting name="returnInstanceForEmptyRow" value="false" />
<setting name="jdbcTypeNameGuessing" value="false" />
<setting name="mapJavaTypeToDbType" value="true" />
<setting name="localCacheEnabled" value="true" />
<setting name="batch" value="BATCH" />
</settings>
```
2. 在Mybatis的Mapper文件中,定义批量插入的SQL语句。例如:
```
<insert id="batchInsert" parameterType="java.util.List">
insert into table_name (column1, column2, column3) values
<foreach collection="list" item="item" separator=",">
(#{item.column1}, #{item.column2}, #{item.column3})
</foreach>
</insert>
```
3. 在Java代码中,使用Mybatis的批量插入功能进行数据插入。例如:
```
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH);
MyMapper mapper = sqlSession.getMapper(MyMapper.class);
List<MyObject> list = new ArrayList<>();
// add data to list
mapper.batchInsert(list);
sqlSession.commit();
sqlSession.close();
```
注意事项:
- Oracle数据库需要设置参数才能支持批量插入功能。在JDBC连接字符串中添加参数“oracle.jdbc.batchUpdateBehavior=2”即可。
- 批量插入数据时,需要注意每次插入的数据量不能太大,否则可能会导致数据库响应变慢。可以根据实际情况调整每次插入的数据量。
阅读全文