Skip to content

Commit aa4ee2f

Browse files
feat: cosmetic changes
1 parent 35f377b commit aa4ee2f

File tree

16 files changed

+90
-91
lines changed

16 files changed

+90
-91
lines changed

dbAndCsvBatch/README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,11 @@ docker compose down && docker compose build && docker compose up -d
2525
## Connect to the MySQL container and check tables and records
2626
docker exec -it mysql-container mysql -u sampleuser -psamplepassword sampledb
2727

28+
mysql> show databases;
2829
mysql> show tables;
2930
mysql> SELECT * FROM member;
30-
mysql> SELECT * FROM member WHERE delete_flag = 0 AND type IN (1, 2, 3);
31+
mysql> SELECT * FROM member WHERE delete_flag = 0 AND type IN (1, 2, 3) ORDER BY type ASC;
32+
mysql> exit;
3133

3234
# DBからEntityクラスを生成した後に実行可能JARを作成するように、default taskを設定している
3335
# Generate the JAR file by executing the default task after creating entity classes from the database

dbAndCsvBatch/build.gradle

+10-14
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
plugins {
2-
id 'org.springframework.boot' version '3.4.0'
3-
id 'io.spring.dependency-management' version '1.1.6'
4-
id 'com.diffplug.spotless' version '6.22.0'
5-
id 'nu.studer.jooq' version '9.0'
6-
id 'java'
7-
id 'project-report'
8-
id 'jacoco'
9-
id 'com.github.spotbugs' version '6.0.26'
10-
id 'idea'
11-
id 'eclipse'
2+
id("org.springframework.boot") version "3.4.0"
3+
id("io.spring.dependency-management") version "1.1.6"
4+
id("com.diffplug.spotless") version "6.22.0"
5+
id("nu.studer.jooq") version "9.0"
6+
id("java")
7+
id("project-report")
8+
id("jacoco")
9+
id("com.github.spotbugs") version "6.0.26"
10+
id("idea")
11+
id("eclipse")
1212
}
1313

1414
group = 'com.example.batch'
@@ -53,10 +53,6 @@ dependencies {
5353
jooqGenerator 'com.mysql:mysql-connector-j'
5454
}
5555

56-
tasks.withType(JavaCompile) {
57-
options.encoding = 'UTF-8'
58-
}
59-
6056
tasks.named('test') {
6157
useJUnitPlatform()
6258
}

dbAndCsvBatch/src/main/java/com/example/batch/DbAndCsvBatchApp.java

+3-7
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,13 @@ public class DbAndCsvBatchApp {
1111
private static final Logger log = LoggerFactory.getLogger(DbAndCsvBatchApp.class);
1212

1313
public static void main(String[] args) {
14-
logOnlyBatchDetails();
14+
logBatchStartupDetails();
1515

1616
SpringApplication.run(DbAndCsvBatchApp.class, args);
1717
}
1818

19-
/**
20-
* バッチの起動引数をログ出力して確認できるようにする
21-
*
22-
* <p>Logs the batch startup arguments for verification.
23-
*/
24-
private static void logOnlyBatchDetails() {
19+
/** Log startup arguments */
20+
private static void logBatchStartupDetails() {
2521
String commandProp = System.getProperty("sun.java.command");
2622
log.info(
2723
"##### KEY:\"sun.java.command\", VALUE:\"{}\"", System.getProperty("sun.java.command"));

dbAndCsvBatch/src/main/java/com/example/batch/job/CsvToDbJob.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.example.batch.job;
22

3-
import com.example.batch.config.BatchNotificationListener;
3+
import com.example.batch.job.listener.BatchNotificationListener;
44
import com.example.batch.logic.CsvToDbLogic;
55
import lombok.RequiredArgsConstructor;
66
import lombok.extern.slf4j.Slf4j;

dbAndCsvBatch/src/main/java/com/example/batch/job/DbToCsvJob.java

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
package com.example.batch.job;
22

3-
import com.example.batch.config.BatchNotificationListener;
3+
import com.example.batch.job.listener.BatchNotificationListener;
44
import com.example.batch.logic.DbToCsvLogic;
55
import lombok.RequiredArgsConstructor;
66
import lombok.extern.slf4j.Slf4j;

dbAndCsvBatch/src/main/java/com/example/batch/config/BatchNotificationListener.java renamed to dbAndCsvBatch/src/main/java/com/example/batch/job/listener/BatchNotificationListener.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package com.example.batch.config;
1+
package com.example.batch.job.listener;
22

33
import lombok.extern.slf4j.Slf4j;
44
import org.springframework.batch.core.JobExecution;
@@ -11,14 +11,14 @@ public class BatchNotificationListener implements JobExecutionListener {
1111
@Override
1212
public void beforeJob(JobExecution jobExecution) {
1313
log.info(
14-
"----------- JOB [Job Name:{}] START! -----------",
14+
"----------- Listener: JOB [Job Name:{}] START! -----------",
1515
jobExecution.getJobInstance().getJobName());
1616
}
1717

1818
@Override
1919
public void afterJob(JobExecution jobExecution) {
2020
log.info(
21-
"----------- JOB [Job Name:{}] FINISHED! status:[{}] -----------",
21+
"----------- Listener: JOB [Job Name:{}] FINISHED! status:[{}] -----------",
2222
jobExecution.getJobInstance().getJobName(),
2323
jobExecution.getStatus());
2424
}

dbAndCsvBatch/src/main/java/com/example/batch/logic/DbToCsvLogic.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
public class DbToCsvLogic implements Tasklet {
2121
private final DbToCsvService dbToCsvService;
2222

23-
@Value("${batch.types:1,2,3}")
23+
@Value("${batch.types:2,3,4}")
2424
private String typesConfig;
2525

2626
@Override
@@ -30,8 +30,8 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext chunkCon
3030
// 起動引数からリストに変換
3131
// Convert the `batch.types` command-line argument into a list of Byte values
3232
List<Byte> types = Arrays.stream(typesConfig.split(",")).map(Byte::valueOf).toList();
33-
34-
BatchResult result = dbToCsvService.execute(types);
33+
String filePath = "members.csv";
34+
BatchResult result = dbToCsvService.execute(types, filePath);
3535

3636
if (result == BatchResult.SUCCESS) {
3737
log.info("Batch process completed successfully.");

dbAndCsvBatch/src/main/java/com/example/batch/repository/MemberRepository.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,13 @@
99
import org.jooq.DSLContext;
1010
import org.springframework.stereotype.Repository;
1111

12-
@RequiredArgsConstructor
1312
@Slf4j
13+
@RequiredArgsConstructor
1414
@Repository
1515
public class MemberRepository {
1616
private final DSLContext dslContext;
1717

1818
public List<MemberRecord> findMembersByTypeAndDeleteFlag(List<Byte> types, Byte deleteFlag) {
19-
log.info("Fetching members with types = {}", types);
20-
2119
return dslContext
2220
.selectFrom(MEMBER)
2321
.where(MEMBER.DELETE_FLAG.eq(deleteFlag))

dbAndCsvBatch/src/main/java/com/example/batch/service/CsvToDbService.java

+1-3
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ public class CsvToDbService {
2323
private final MemberRepository memberRepository;
2424

2525
/**
26-
* CSVを読み取って、データベースに流し込む
26+
* CSVを読み取って、DBに流し込む
2727
*
2828
* <p>Reads data from a CSV file and inserts it into the database.
2929
*/
@@ -61,14 +61,12 @@ private List<MemberRecord> loadCsvData(String csvFilePath)
6161

6262
List<MemberRecord> memberRecords = new ArrayList<>();
6363
try (CSVReader reader = new CSVReader(new FileReader(csvFilePath))) {
64-
// Skip the header row
6564
String[] header = reader.readNext();
6665
if (header == null) {
6766
log.warn("The CSV file is empty. Processing will be terminated.");
6867
return memberRecords;
6968
}
7069

71-
// Map data rows to MemberRecord objects
7270
String[] line;
7371
while ((line = reader.readNext()) != null) {
7472
MemberRecord memberRecord = new MemberRecord();

dbAndCsvBatch/src/main/java/com/example/batch/service/DbToCsvService.java

+26-20
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,18 @@ public class DbToCsvService {
1818
private final MemberRepository memberRepository;
1919

2020
/**
21-
* データベースからデータを取得してCSVに出力する
21+
* DBのレコードをCSVに出力する
2222
*
2323
* <p>Retrieve data from the database and export it to a CSV file.
2424
*/
25-
public BatchResult execute(List<Byte> types) throws Exception {
25+
public BatchResult execute(List<Byte> types, String filePath) throws Exception {
2626

2727
byte deleteFlag = 0;
2828
List<MemberRecord> memberEntityList =
2929
memberRepository.findMembersByTypeAndDeleteFlag(types, deleteFlag);
3030

3131
if (!memberEntityList.isEmpty()) {
32-
String csvFileName = "members.csv";
33-
writeCsv(memberEntityList, csvFileName);
32+
writeCsv(memberEntityList, filePath);
3433
} else {
3534
log.warn("No data found matching the criteria.");
3635
return BatchResult.NODATA;
@@ -39,25 +38,32 @@ public BatchResult execute(List<Byte> types) throws Exception {
3938
return BatchResult.SUCCESS;
4039
}
4140

42-
private void writeCsv(List<MemberRecord> members, String filePath) throws IOException {
41+
private void writeCsv(List<MemberRecord> records, String filePath) throws IOException {
4342
try (CSVWriter writer = new CSVWriter(new FileWriter(filePath))) {
44-
String[] header = {
45-
"id", "type", "name", "email", "phone", "address", "deleteFlag", "createdAt", "updatedAt"
46-
};
47-
writer.writeNext(header);
48-
49-
for (MemberRecord member : members) {
43+
writer.writeNext(
44+
new String[] {
45+
"id",
46+
"type",
47+
"name",
48+
"email",
49+
"phone",
50+
"address",
51+
"deleteFlag",
52+
"createdAt",
53+
"updatedAt"
54+
});
55+
for (MemberRecord record : records) {
5056
writer.writeNext(
5157
new String[] {
52-
String.valueOf(member.getId()),
53-
String.valueOf(member.getType()),
54-
member.getName(),
55-
member.getEmail(),
56-
member.getPhone(),
57-
member.getAddress(),
58-
String.valueOf(member.getDeleteFlag()),
59-
String.valueOf(member.getCreatedAt()),
60-
String.valueOf(member.getUpdatedAt())
58+
String.valueOf(record.getId()),
59+
String.valueOf(record.getType()),
60+
record.getName(),
61+
record.getEmail(),
62+
record.getPhone(),
63+
record.getAddress(),
64+
String.valueOf(record.getDeleteFlag()),
65+
String.valueOf(record.getCreatedAt()),
66+
String.valueOf(record.getUpdatedAt())
6167
});
6268
}
6369
}

dbAndCsvBatch/src/test/java/com/example/batch/service/CsvToDbServiceTest.java

+2-10
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ class CsvToDbServiceTest {
2828

2929
@Mock private MemberRepository memberRepository;
3030

31-
@TempDir Path tempDir; // JUnitが一時ディレクトリを提供
31+
@TempDir Path tempDir;
3232

3333
private File tempCsvFile;
3434

@@ -37,11 +37,9 @@ void setUp() throws IOException {
3737
tempCsvFile = tempDir.resolve("members.csv").toFile();
3838
log.info("Temporary CSV file created at: {}", tempCsvFile.getAbsolutePath());
3939

40-
// テスト用のCSVファイルを作成
4140
try (FileWriter fileWriter = new FileWriter(tempCsvFile);
4241
CSVWriter csvWriter = new CSVWriter(fileWriter)) {
4342

44-
// ヘッダー行を追加
4543
csvWriter.writeNext(
4644
new String[] {
4745
"id",
@@ -55,7 +53,6 @@ void setUp() throws IOException {
5553
"updatedAt"
5654
});
5755

58-
// データ行を追加
5956
csvWriter.writeNext(
6057
new String[] {
6158
"1",
@@ -74,17 +71,14 @@ void setUp() throws IOException {
7471

7572
@Test
7673
void testExecuteSuccess() throws Exception {
77-
// テスト実行
7874
BatchResult result = csvToDbService.execute(tempCsvFile.getAbsolutePath());
7975

80-
// 検証
8176
assertThat(result).isEqualTo(BatchResult.SUCCESS);
8277
Mockito.verify(memberRepository, Mockito.times(1)).bulkInsert(Mockito.anyList());
8378
}
8479

8580
@Test
8681
void testExecuteNoData() throws Exception {
87-
// 空のCSVファイルを作成
8882
File emptyCsvFile = tempDir.resolve("empty.csv").toFile();
8983
try (FileWriter fileWriter = new FileWriter(emptyCsvFile);
9084
CSVWriter csvWriter = new CSVWriter(fileWriter)) {
@@ -99,13 +93,11 @@ void testExecuteNoData() throws Exception {
9993
"deleteFlag",
10094
"createdAt",
10195
"updatedAt"
102-
}); // ヘッダーのみ
96+
});
10397
}
10498

105-
// テスト実行
10699
BatchResult result = csvToDbService.execute(emptyCsvFile.getAbsolutePath());
107100

108-
// 検証
109101
assertThat(result).isEqualTo(BatchResult.NODATA);
110102
Mockito.verify(memberRepository, Mockito.never()).bulkInsert(Mockito.anyList());
111103
}

dbAndCsvBatch/src/test/java/com/example/batch/service/DbToCsvServiceTest.java

+4-7
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,10 @@ void setUp() {
2727
MockitoAnnotations.openMocks(this);
2828
}
2929

30+
String filePath = "members.csv";
31+
3032
@Test
3133
void testExecute_Success() throws Exception {
32-
// Arrange: モックデータの準備
3334
List<MemberRecord> mockData =
3435
List.of(
3536
createMockMember(
@@ -60,10 +61,8 @@ void testExecute_Success() throws Exception {
6061
when(memberRepository.findMembersByTypeAndDeleteFlag(anyList(), eq((byte) 0)))
6162
.thenReturn(mockData);
6263

63-
// Act
64-
BatchResult result = dbToCsvService.execute(List.of((byte) 1, (byte) 2, (byte) 3));
64+
BatchResult result = dbToCsvService.execute(List.of((byte) 1, (byte) 2, (byte) 3), filePath);
6565

66-
// Assert
6766
assertThat(result).isEqualTo(BatchResult.SUCCESS);
6867
verify(memberRepository, times(1)).findMembersByTypeAndDeleteFlag(anyList(), eq((byte) 0));
6968

@@ -79,10 +78,8 @@ void testExecute_NoData() throws Exception {
7978
when(memberRepository.findMembersByTypeAndDeleteFlag(anyList(), eq((byte) 0)))
8079
.thenReturn(List.of());
8180

82-
// Act
83-
BatchResult result = dbToCsvService.execute(List.of((byte) 1, (byte) 2, (byte) 3));
81+
BatchResult result = dbToCsvService.execute(List.of((byte) 1, (byte) 2, (byte) 3), filePath);
8482

85-
// Assert
8683
assertThat(result).isEqualTo(BatchResult.NODATA);
8784
verify(memberRepository, times(1)).findMembersByTypeAndDeleteFlag(anyList(), eq((byte) 0));
8885
}

gradle/wrapper/gradle-wrapper.properties

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
distributionBase=GRADLE_USER_HOME
22
distributionPath=wrapper/dists
3-
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
3+
distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip
44
networkTimeout=10000
55
validateDistributionUrl=true
66
zipStoreBase=GRADLE_USER_HOME

skeletonBatch/build.gradle

+10-13
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
plugins {
2-
id 'org.springframework.boot' version '3.4.0'
3-
id 'io.spring.dependency-management' version '1.1.6'
4-
id 'com.diffplug.spotless' version '6.22.0'
5-
id 'java'
6-
id 'jacoco'
7-
id 'project-report'
8-
id 'com.github.spotbugs' version '6.0.26'
9-
id 'idea'
10-
id 'eclipse'
2+
id("org.springframework.boot") version "3.4.0"
3+
id("io.spring.dependency-management") version "1.1.6"
4+
id("com.diffplug.spotless") version "6.22.0"
5+
id("nu.studer.jooq") version "9.0"
6+
id("java")
7+
id("project-report")
8+
id("jacoco")
9+
id("com.github.spotbugs") version "6.0.26"
10+
id("idea")
11+
id("eclipse")
1112
}
1213

1314
group = 'com.example.batch'
@@ -36,10 +37,6 @@ dependencies {
3637
testImplementation 'org.springframework.batch:spring-batch-test'
3738
}
3839

39-
tasks.withType(JavaCompile) {
40-
options.encoding = 'UTF-8'
41-
}
42-
4340
tasks.named('test') {
4441
useJUnitPlatform()
4542
}

0 commit comments

Comments
 (0)