[ElectionPJT] 7. Survey_Entity, Repository, Service
47265 단어 ElectionPJTElectionPJT
1. 지원 기능
- 설문조사 추가
- 설문조사 삭제
2. Entity
@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Survey {
@Id @GeneratedValue
@Column(name = "survey_id")
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "city_id")
private City city;
private LocalDateTime surveyDate;
private String executor;
private String requester;
@OneToMany(mappedBy = "survey", cascade = CascadeType.ALL)
private List<Rating> ratings = new ArrayList<>();
@Builder
public Survey(City city, LocalDateTime surveyDate, String executor, String requester) {
this.city = city;
this.surveyDate = surveyDate;
this.executor = executor;
this.requester = requester;
}
//== 연관관계 편의 메서드 ==//
public void addRating(Rating rating) {
ratings.add(rating);
rating.setSurvey(this);
}
}
- 빌더가 추가되었습니다.
- 연관관계 편의 메서드가 추가되었습니다.
3. Repository
@Repository
@RequiredArgsConstructor
public class SurveyRepository {
private final EntityManager em;
public void save(Survey survey) {
em.persist(survey);
}
public void remove(Survey survey) {
em.remove(survey);
}
public Survey findOne(Long id) {
return em.createQuery("select s from Survey s" +
" join fetch s.ratings r" +
" where s.id = :id", Survey.class)
.setParameter("id", id)
.getResultList()
.get(0);
}
public List<Survey> findAllByCityId(Long cityId) {
return em.createQuery("select s from Survey s" +
" join fetch s.ratings r" +
" where s.city.id = :cityId order by s.surveyDate desc, r.candidateNumber", Survey.class)
.setParameter("cityId", cityId)
.getResultList();
}
}
4. Service
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class SurveyService {
private final CityRepository cityRepository;
private final SurveyRepository surveyRepository;
@Transactional
public Long join(SurveyRequestDto surveyRequestDto) {
Long cityId = surveyRequestDto.getCityId();
City city = cityRepository.findOne(cityId);
Survey survey = surveyRequestDto.toEntity(city);
List<String> names = surveyRequestDto.getNames();
List<Double> rates = surveyRequestDto.getRates();
for (int i = 0; i < surveyRequestDto.getNames().size(); i++) {
Rating rating = new Rating(i+1, names.get(i), rates.get(i));
survey.addRating(rating);
}
surveyRepository.save(survey);
return survey.getId();
}
@Transactional
public void delete(Long surveyId) {
Survey survey = surveyRepository.findOne(surveyId);
surveyRepository.remove(survey);
}
public SurveyResponseDto findSurvey(Long surveyId) {
Survey survey = surveyRepository.findOne(surveyId);
return new SurveyResponseDto(survey);
}
public List<SurveyResponseDto> findSurveyList(Long cityId) {
List<Survey> surveyList = surveyRepository.findAllByCityId(cityId);
return surveyList.stream()
.map(SurveyResponseDto::new)
.collect(Collectors.toList());
}
}
5. DTO
RequestDto
@Getter @Setter
@Builder
@AllArgsConstructor
public class SurveyRequestDto {
private Long cityId;
private LocalDateTime surveyDate;
private String executor;
private String requester;
private List<String> names;
private List<Double> rates;
public Survey toEntity(City city) {
return Survey.builder()
.city(city)
.surveyDate(surveyDate)
.executor(executor)
.requester(requester)
.build();
}
}
ResponseDto
@Getter @Setter
@Builder
@AllArgsConstructor
public class SurveyResponseDto {
private LocalDateTime surveyDate;
private String executor;
private String requester;
private List<String> names = new ArrayList<>();
private List<Double> rates = new ArrayList<>();
public SurveyResponseDto(Survey survey) {
this.surveyDate = survey.getSurveyDate();
this.executor = survey.getExecutor();
this.requester = survey.getRequester();
for(int i = 0; i < survey.getRatings().size(); i++) {
names.add(survey.getRatings().get(i).getCandidateName());
rates.add(survey.getRatings().get(i).getRate());
}
}
}
6. Test
테스트 요구사항
- 설문조사 추가
- 설문조사 삭제
테스트 코드
@SpringBootTest
@Transactional
class SurveyServiceTest {
@Autowired CityRepository cityRepository;
@Autowired SurveyService surveyService;
@Test
public void 설문조사_추가() throws Exception {
//given
City city = createCity();
List<String> names = new ArrayList<>();
names.add("candidate1"); names.add("candidate2"); names.add("candidate3");
List<Double> rates = new ArrayList<>();
rates.add(11.1); rates.add(22.2); rates.add(33.3);
SurveyRequestDto surveyRequestDto = SurveyRequestDto.builder()
.cityId(city.getId())
.surveyDate(LocalDateTime.now())
.executor("executor")
.requester("requester")
.names(names)
.rates(rates)
.build();
//when
Long surveyId = surveyService.join(surveyRequestDto);
//then
Assertions.assertEquals(3, surveyService.findSurvey(surveyId).getNames().size());
Assertions.assertEquals(11.1, surveyService.findSurvey(surveyId).getRates().get(0));
}
@Test
public void 설문조사_삭제() throws Exception {
//given
City city = createCity();
List<String> names = new ArrayList<>();
names.add("candidate1"); names.add("candidate2"); names.add("candidate3");
List<Double> rates = new ArrayList<>();
rates.add(11.1); rates.add(22.2); rates.add(33.3);
SurveyRequestDto surveyRequestDto = SurveyRequestDto.builder()
.cityId(city.getId())
.surveyDate(LocalDateTime.now())
.executor("executor")
.requester("requester")
.names(names)
.rates(rates)
.build();
Long surveyId = surveyService.join(surveyRequestDto);
//when
surveyService.delete(surveyId);
//then
try {
surveyService.findSurvey(surveyId);
} catch (IndexOutOfBoundsException e) {
return;
}
Assertions.fail();
}
private City createCity() {
District district = new District("서울", "서울특별시 종로구", "서울 종로");
City city = new City(district);
cityRepository.save(city);
return city;
}
}
테스트 결과
Author And Source
이 문제에 관하여([ElectionPJT] 7. Survey_Entity, Repository, Service), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@mincho920/ElectionPJT-7.-SurveyEntity-Repository-Service저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)