반응형
Spring Boot 초기 데이터 생성 - CommandLineRunner 활용 (2)
sql문을 활용하지 않고, JPA Repository를 활용하여 json 파일을 읽어서 초기 데이터 생성
- Entity/Model: Sample
- Sample Repository
- 초기 데이터용 파일 (json): init_sample.json - Sample List
- 초기 데이터 읽기 / DB 적재 Service
<< Entity/Model >>
[ Sample.java ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
|
package com.home.test.sample.domain;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@Table(name = "tb_sample")
@Entity
public class Sample implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long sampleId;
@NotNull
private String sampleName;
@NotNull
@Column(columnDefinition = "INTEGER DEFAULT 0")
private int sampleTag;
@Lob
private String sampleDescription;
@Column(columnDefinition = "BOOLEAN DEFAULT false")
private boolean isEnabled;
public Sample() {
}
public Sample(Long sampleId, String sampleName, int sampleTag, String sampleDescription, boolean isEnabled) {
this.sampleId = sampleId;
this.sampleName = sampleName;
this.sampleTag = sampleTag;
this.sampleDescription = sampleDescription;
this.isEnabled = isEnabled;
}
public Long getSampleId() {
return sampleId;
}
public void setSampleId(Long sampleId) {
this.sampleId = sampleId;
}
public String getSampleName() {
return sampleName;
}
public void setSampleName(String sampleName) {
this.sampleName = sampleName;
}
public int getSampleTag() {
return sampleTag;
}
public void setSampleTag(int sampleTag) {
this.sampleTag = sampleTag;
}
public String getSampleDescription() {
return sampleDescription;
}
public void setSampleDescription(String sampleDescription) {
this.sampleDescription = sampleDescription;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean enabled) {
isEnabled = enabled;
}
@Override
public String toString() {
return "Sample{" +
"sampleId=" + sampleId +
", sampleName='" + sampleName + '\'' +
", sampleTag=" + sampleTag +
", sampleDescription='" + sampleDescription + '\'' +
", isEnabled=" + isEnabled +
'}';
}
}
|
<< Sample Entity용 Repository, Service >>
[ SampleRepository.java ]
1
2
3
4
5
6
7
8
|
package com.home.test.sample.repository;
import com.home.test.sample.domain.Sample;
import org.springframework.data.jpa.repository.JpaRepository;
public interface SampleRepository extends JpaRepository<Sample, Long> {
}
|
초기 데이터용 파일 (json): init_sample.json
[ init_sample.json ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
{
"sample": [
{
"sampleName": "sample 1-001",
"sampleTag": 0,
"sampleDescription": "sample description 1-001",
"enabled": true
},
{
"sampleName": "sample 1-002",
"sampleTag": 1,
"sampleDescription": "sample description 1-002",
"enabled": true
},
{
"sampleName": "sample 1-003",
"sampleTag": 0,
"sampleDescription": "sample description 1-003",
"enabled": false
}
]
}
|
초기 데이터 읽기 / DB 적재 Service
[ InitSampleService.java ]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
package com.home.test.init.service;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.home.test.sample.domain.Sample;
import com.home.test.sample.repository.SampleRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Service;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class InitSampleService implements CommandLineRunner {
private Logger log = LoggerFactory.getLogger(InitSampleService.class);
private final String FILE_INIT_SAMPLE = "config/init_sample.json";
private final SampleRepository sampleRepository;
public InitSampleService(SampleRepository sampleRepository) {
this.sampleRepository = sampleRepository;
}
@Override
public void run(String... args) throws Exception {
List<Sample> sampleList = new ArrayList<>();
sampleList = getInitSamplesFromFile();
if (sampleList == null || sampleList.size() == 0) {
throw new IllegalArgumentException("no data in init data file.");
}
for (Sample sample : sampleList) {
sampleRepository.save(sample);
}
}
private List<Sample> getInitSamplesFromFile() throws IOException {
List<Sample> sampleList = new ArrayList<>();
try (InputStream is = getStreamFromResource(FILE_INIT_SAMPLE)) {
JsonNode sampleNode = getSampleNode(is);
sampleList = getSampleListFromNode(sampleNode);
}
return sampleList;
}
private InputStream getStreamFromResource(String fileLocation) {
ClassLoader classLoader = InitSampleService.class.getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream(fileLocation);
if (inputStream == null) {
throw new IllegalArgumentException("init data file \"" + fileLocation + "\" not found.");
} else {
return inputStream;
}
}
private JsonNode getSampleNode(InputStream is) {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode sampleNode = null;
try (DataInputStream dis = new DataInputStream(is)) {
sampleNode = objectMapper.readTree(dis).path("sample");
} catch (IOException io) {
io.printStackTrace();
}
return sampleNode;
}
private List<Sample> getSampleListFromNode(JsonNode sampleNode) {
ObjectMapper objectMapper = new ObjectMapper();
List<Sample> sampleList = objectMapper.convertValue(sampleNode, new TypeReference<List<Sample>>() {
}).stream().collect(Collectors.toList());
return sampleList;
}
}
|
<< Spring Boot 기동 후 h2-console 확인 >>
[ h2-console 접속 ]
[ tb_sample 테이블 확인 ]
반응형
'스프링 (Spring) > Spring Boot' 카테고리의 다른 글
[Spring Boot 실습 #5] Swagger UI 활용 (2) - spring fox 추가 (0) | 2021.05.13 |
---|---|
[Spring Boot 실습 #5] Swagger UI 활용 (1) - Swagger 정의 및 활용 (0) | 2021.05.13 |
[Spring Boot 실습 #4] 초기 데이터 생성 - CommandLineRunner 활용 (1) (0) | 2021.05.02 |
[Spring Boot 실습 #3] Runtime에 WAR파일 내부 json 파일 읽기 (3) - 테스트 (0) | 2021.02.01 |
[Spring Boot 실습 #3] Runtime에 WAR파일 내부 json 파일 읽기 (2) - 테스트 (0) | 2021.01.20 |