50일차 항해일지
2021. 11. 2. 21:57ㆍ항해99/TIL
728x90
오늘 한 일
더미데이터가 아닌 실제 주소를 넣은 실제 데이터 넣기
기존
@NoArgsConstructor
@Component
public class SimpleListener implements ApplicationListener<ApplicationStartedEvent> {
@Autowired
private EntityManagerFactory entityManagerFactory;
@Autowired
private CampingRepository campingRepository;
@Autowired
private UserMakeRepository userMakeRepository;
@Autowired
private WeatherRepository weatherRepository;
@Override
@Transactional
public void onApplicationEvent(ApplicationStartedEvent event) {
User user = new User("기남", "asdf", "salmon2");
em.persist(user);
for (int i = 0 ; i<10; i++){
Camping newCamping = new Camping("테스트용 캠핑 제목" + i,
"테스트용 캠핑 본문" + i, "테스트용 이미지" + i, "캠핑 데이터" + i);
em.persist(newCamping);
Location newLocation = new Location(3.2, 1.5, "더미 주소", "대구", newCamping);
em.persist(newLocation);
Star newStar = new Star("moonrise", "moonSet", 3L, newLocation);
em.persist(newStar);
for (int j = 12; j < 15; j++) {
Weather newWeather = new Weather(
"humidity",
"weather",
"temperature",
"maxTemperature",
"minTemperature",
"rainPercent",
j+"00", //1200 1300 1400
"나쁨",
"20211029",
newLocation
);
em.persist(newWeather);
}
}
}
}
ApplicationListener
와<ApplicationStartedEvent>
를 통해서 서버가 실행 될 때 실행 되는 함수를 작성한다.- 서버가 시작 될때
EntityManerger
를 통해서 db에 데이터를 저장할 수 있다. - 데이터의 신뢰성에 맞게 데이터를 넣는게 아니라 테스트용의 타입만 맞춘 데이터를 저장한다.
변경
@NoArgsConstructor
//@Component
public class SimpleListener implements ApplicationListener<ApplicationStartedEvent> {
@Autowired
UserRepository userRepository;
@Autowired
CampingRepository campingRepository;
@Autowired
API api;
@SneakyThrows
@Override
@Transactional
public void onApplicationEvent(ApplicationStartedEvent event) {
User user = new User("기남", "asdf", "salmon2");
userRepository.save(user);
int count = 0;
for (CampingList value : CampingList.values()) {
Camping campingData = new Camping(value.getName(), value.getAddress(), value.getAddress(),
value.getImgSrc(), user, "campingData");
campingRepository.save(campingData);
count++;
}
List<Camping> campingList = campingRepository.findAll();
for (Camping camping : campingList) {
LocationStarMoonDustDto infoByAddress = api.findInfoByAddress(camping.getAddress());
api.saveStarLocationWeather(camping, infoByAddress);
}
}
}
API
라는 이름의 클래스가 모든 외부 api를 관리하는 통합 Class 를 제작하였다.- 단순히 API 클래스를 인스턴스를 받아서
findInfoByAddress(String)
와saveStarLocationWeather(Camping, Object)
를 통해서 간단하게 실제 데이터를 저장할 수 있다.