To create a MyBatisBatchItemWriter
using XML configuration in a Spring Batch job, follow these steps:
1. Add Dependencies
Make sure you have the required dependencies in your pom.xml
:
xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>4.3.4</version>
</dependency>
2. Configure SqlSessionFactory in applicationContext.xml
xml
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydatabase" />
<property name="username" value="root" />
<property name="password" value="password" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
</bean>
3. Define the MyBatisBatchItemWriter
Bean
xml
<bean id="myBatisBatchItemWriter" class="org.mybatis.spring.batch.MyBatisBatchItemWriter">
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
<property name="statementId" value="com.example.mapper.MyMapper.insertItem" />
</bean>
sqlSessionFactory
: Refers to the SqlSessionFactory
bean that handles the DB connection.statementId
: Maps to the ID of the SQL statement defined in the mapper XML.
4. Define a Mapper XML
Create a mapper XML file named MyMapper.xml
:
xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.MyMapper">
<insert id="insertItem" parameterType="com.example.model.MyItem">
INSERT INTO my_table (column1, column2, column3)
VALUES (#{field1}, #{field2}, #{field3})
</insert>
</mapper>
5. Integrate MyBatisBatchItemWriter
into Spring Batch Job Config
xml
<batch:job id="myJob">
<batch:step id="step1">
<batch:tasklet>
<batch:chunk reader="myReader" writer="myBatisBatchItemWriter" commit-interval="10" />
</batch:tasklet>
</batch:step>
</batch:job>
6. Define the Reader
xml
<bean id="myReader" class="org.springframework.batch.item.database.JdbcCursorItemReader">
<property name="dataSource" ref="dataSource" />
<property name="sql" value="SELECT * FROM source_table" />
<property name="rowMapper">
<bean class="com.example.mapper.MyItemRowMapper" />
</property>
</bean>
7. Final Notes
- Namespace in Mapper: Should match the fully qualified class name of the interface.
- ParameterType: Must match the model class used in your
MyBatisBatchItemWriter
.
This setup enables you to use MyBatisBatchItemWriter
for writing batches of records into the database using XML configuration in Spring Batch.