gradle /dependencies
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-batch'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.h2database:h2'
runtimeOnly 'mysql:mysql-connector-java'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.batch:spring-batch-test'
}
@EnableBatchProcessing //배치 기능 활성화
@SpringBootApplication
public class PlanetApplication {
public static void main(String[] args) {
SpringApplication.run(PlanetApplication.class, args);
}
}
spring:
datasource:
hikari:
jdbc-url: jdbc:mysql://localhost:3306/springBatch
username: [이름]
password: [비밀번호]
driver-class-name: com.mysql.cj.jdbc.Driver
config:
activate:
on-profile: mysql
spring.batch.job.names: ${job.name:NONE}
Grade
@NoArgsConstructor
@Entity
@Table
@Getter
@Setter
public class Grade {
@Id
@Column
private String user_id; //user 이메일, 사용자 아이디
@Column
private String grade; // 등급
}
GradeJobConfig
@Slf4j
@RequiredArgsConstructor
@Configuration
public class GradeJobConfig {
private final JobBuilderFactory jobBuilderFactory;
private final StepBuilderFactory stepBuilderFactory;
private final EntityManagerFactory entityManagerFactory;
private static final int chunkSize = 10;
@Bean
public Job gradeJob() {
return jobBuilderFactory.get("gradeJob")
.start(gradeStep())
.build();
}
@Bean
public Step gradeStep() {
return stepBuilderFactory.get("gradeStep")
.<Grade, Grade>chunk(chunkSize)
.reader(gradeReader())
.writer(gradeWriter())
.build();
}
@Bean
public JpaPagingItemReader<Grade> gradeReader() {
return new JpaPagingItemReaderBuilder<Grade>()
.name("gradeReader")
.entityManagerFactory(entityManagerFactory)
.pageSize(chunkSize)
.queryString("SELECT p FROM Grade p WHERE grade='A'")
.build();
}
@Bean
public ItemWriter<Grade> gradeWriter() {
return new ItemWriter<Grade>() {
@Override
public void write(List<? extends Grade> items) throws Exception {
for (Grade item : items) {
System.out.println("user_id = "+ item.getUser_id());
}
}
};
}
}
A등급인 유저의 user_id가 출력된다.