[spring batch] 등급 확인하기

dev-log·2021년 12월 17일
0

Spring Batch

목록 보기
7/7
  1. spring boot 생성하기

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'
}
  1. 배치 활성화
@EnableBatchProcessing //배치 기능 활성화 
@SpringBootApplication
public class PlanetApplication {

	public static void main(String[] args) {
		SpringApplication.run(PlanetApplication.class, args);
	}

}
  1. db 설정 (mysql)
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}
  1. 도메인 생성

    Grade

@NoArgsConstructor
@Entity
@Table
@Getter
@Setter
public class Grade {
    @Id
    @Column
    private String user_id; //user 이메일, 사용자 아이디

    @Column
    private String grade; // 등급

}
  1. job 생성

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가 출력된다.

profile
배운 걸 기록하는 곳입니다.

0개의 댓글

Powered by GraphCDN, the GraphQL CDN