springbatch 入门案例
时间: 2023-08-06 15:07:03 浏览: 109
好的,这是一个使用Spring Batch实现读取CSV文件并写入数据库的入门案例。首先,你需要设置Spring Batch的环境,包括以下依赖:
```xml
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-core</artifactId>
<version>${spring.batch.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.batch</groupId>
<artifactId>spring-batch-infrastructure</artifactId>
<version>${spring.batch.version}</version>
</dependency>
```
接下来,你需要创建一个Job,Job可以包含一个或多个Step,每个Step都可以包含一个或多个Tasklet或Chunk。我们将使用FlatFileItemReader读取CSV文件,然后将数据写入数据库。
```java
@Configuration
public class BatchConfig {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private DataSource dataSource;
@Bean
public FlatFileItemReader<User> reader() {
FlatFileItemReader<User> reader = new FlatFileItemReader<>();
reader.setResource(new ClassPathResource("users.csv"));
reader.setLineMapper(new DefaultLineMapper<User>() {{
setLineTokenizer(new DelimitedLineTokenizer() {{
setNames(new String[]{"firstName", "lastName", "email"});
}});
setFieldSetMapper(new BeanWrapperFieldSetMapper<User>() {{
setTargetType(User.class);
}});
}});
return reader;
}
@Bean
public JdbcBatchItemWriter<User> writer() {
JdbcBatchItemWriter<User> writer = new JdbcBatchItemWriter<>();
writer.setItemSqlParameterSourceProvider(new BeanPropertyItemSqlParameterSourceProvider<>());
writer.setSql("INSERT INTO user (first_name, last_name, email) VALUES (:firstName, :lastName, :email)");
writer.setDataSource(dataSource);
return writer;
}
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<User, User>chunk(10)
.reader(reader())
.writer(writer())
.build();
}
@Bean
public Job importUserJob() {
return jobBuilderFactory.get("importUserJob")
.incrementer(new RunIdIncrementer())
.flow(step1())
.end()
.build();
}
}
```
在上面的代码中,我们定义了一个FlatFileItemReader,它将从CSV文件中读取数据,然后我们使用JdbcBatchItemWriter将数据写入数据库中。Step包含了reader和writer,它们分别读取和写入数据。最后我们定义了一个Job,它包含了一个步骤(step),并使用RunIdIncrementer来确保每次运行Job都会生成一个唯一的ID。
现在你可以运行这个Job了,只需要注入JobLauncher并调用它的run方法即可:
```java
@Autowired
private JobLauncher jobLauncher;
@Autowired
private Job importUserJob;
public void runJob() throws Exception {
JobParameters jobParameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.toJobParameters();
jobLauncher.run(importUserJob, jobParameters);
}
```
这样就完成了一个简单的使用Spring Batch的读取CSV文件并写入数据库的入门案例。
阅读全文