基于spring batch通过mybatis plus将itemreader读出来的person,进行itemwriter的DB写入
时间: 2024-04-01 11:36:03 浏览: 286
好的,针对你的问题,我可以给出以下基本的代码实现:
1. 首先,在Spring Batch的配置文件中配置MyBatis Plus的SqlSessionFactoryBean,如下所示:
```java
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
// 省略其他配置
@Bean
public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
return sessionFactory;
}
// 省略其他配置
}
```
2. 接下来,我们定义一个ItemReader,从数据源中读取Person对象:
```java
@Component
public class PersonItemReader implements ItemReader<Person> {
private final PersonMapper personMapper;
private int nextPersonIndex;
private List<Person> persons;
public PersonItemReader(PersonMapper personMapper) {
this.personMapper = personMapper;
}
@Override
public Person read() throws Exception {
if (persons == null) {
persons = personMapper.selectList(null);
}
if (nextPersonIndex < persons.size()) {
return persons.get(nextPersonIndex++);
} else {
return null;
}
}
}
```
3. 然后,我们定义一个ItemWriter,将读取到的Person对象写入到数据库中:
```java
@Component
public class PersonItemWriter implements ItemWriter<Person> {
private final PersonMapper personMapper;
public PersonItemWriter(PersonMapper personMapper) {
this.personMapper = personMapper;
}
@Override
public void write(List<? extends Person> persons) throws Exception {
for (Person person : persons) {
personMapper.insert(person);
}
}
}
```
4. 最后,在Job的配置文件中,使用上述的ItemReader和ItemWriter:
```java
@Configuration
public class JobConfiguration {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private PersonItemReader personItemReader;
@Autowired
private PersonItemWriter personItemWriter;
@Bean
public Step step() {
return stepBuilderFactory.get("step")
.<Person, Person>chunk(10)
.reader(personItemReader)
.writer(personItemWriter)
.build();
}
@Bean
public Job job() {
return jobBuilderFactory.get("job")
.start(step())
.build();
}
}
```
以上就是基于Spring Batch和MyBatis Plus实现将ItemReader读出的Person对象写入数据库的基本代码实现。
阅读全文