MyBatis Batch Data Insert Guide
In MyBatis, you can use batch operations to store a large amount of data in bulk. Here is one way to implement it:
- First, define a Mapper interface to perform batch insert operations. In the interface, use the @Insert annotation to define the insert SQL statement, and add a List parameter to pass in the list of data to be inserted.
public interface MyMapper {
@Insert("INSERT INTO my_table (column1, column2) VALUES (#{item.field1}, #{item.field2})")
void batchInsert(List<MyData> dataList);
}
- Create a MyData class to encapsulate the data to be inserted.
public class MyData {
private String field1;
private String field2;
// getter and setter
}
- Configure data source and batch operation settings in the configuration file.
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- 数据源配置 -->
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="my_mapper.xml"/>
</mappers>
<settings>
<setting name="jdbcTypeForNull" value="NULL"/>
<setting name="cacheEnabled" value="true"/>
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
</configuration>
- Create an XML file to configure batch insertion SQL statements.
<mapper namespace="com.example.MyMapper">
<insert id="batchInsert" parameterType="java.util.List">
<foreach collection="list" item="item" separator=";">
INSERT INTO my_table (column1, column2) VALUES (#{item.field1}, #{item.field2})
</foreach>
</insert>
</mapper>
- Create a SqlSessionFactory for MyBatis in the code, use this SessionFactory to retrieve Mapper objects, and then call the batch insert method.
public class Main {
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession session = sqlSessionFactory.openSession();
try {
MyMapper mapper = session.getMapper(MyMapper.class);
List<MyData> dataList = new ArrayList<>();
// 添加要插入的数据到dataList
mapper.batchInsert(dataList);
session.commit();
} finally {
session.close();
}
}
}
By following the above steps, you can achieve the bulk data storage functionality of MyBatis. Keep in mind that in actual use, configurations can be adjusted and optimized according to specific needs to improve the efficiency of inserting data.