Skip to content

Commit

Permalink
[fix] refactor. 알코올타입으로 술정보 조회 기능 추가.
Browse files Browse the repository at this point in the history
  • Loading branch information
dongseoki committed Jan 7, 2024
1 parent 1af0cfe commit b17a8a3
Show file tree
Hide file tree
Showing 10 changed files with 172 additions and 42 deletions.
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
package com.bside.bside_311.component;

import com.bside.bside_311.dto.AlcoholSearchCondition;
import com.bside.bside_311.entity.Alcohol;
import com.bside.bside_311.entity.AlcoholType;
import com.bside.bside_311.entity.Post;
import com.bside.bside_311.entity.PostAlcohol;
import com.bside.bside_311.entity.YesOrNo;
import com.bside.bside_311.repository.AlcoholRepository;
import com.bside.bside_311.repository.AlcoholTypeRepository;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class AlcoholManager {
private final AlcoholRepository alcoholRepository;
private final AlcoholTypeRepository alcoholTypeRepository;

public void connectAlcoholWithPost(Long alcoholNo, String alcoholFeature, Post post) {
Alcohol alcohol = alcoholRepository.findByIdAndDelYnIs(alcoholNo, YesOrNo.N).orElseThrow(
Expand All @@ -20,4 +27,22 @@ public void connectAlcoholWithPost(Long alcoholNo, String alcoholFeature, Post p
post.addPostAlcohol(postAlcohol);
alcohol.addPostAlcohol(postAlcohol);
}

public Page<Alcohol> searchAlcohol(Pageable pageable, String searchKeyword,
Long alcoholType) {
if (ObjectUtils.isNotEmpty(alcoholType)) {
AlcoholType alcoholType1 = alcoholTypeRepository.findByIdAndDelYnIs(alcoholType, YesOrNo.N)
.orElseThrow(
() -> new IllegalArgumentException(
"술 종류가 존재하지 않습니다."));
}
// 술 종류 fetch join
return alcoholRepository.searchAlcoholPage(AlcoholSearchCondition.builder()
.searchKeyword(
searchKeyword)
.alcoholType(
alcoholType)
.build(),
pageable);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Positive;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
Expand Down Expand Up @@ -102,9 +103,13 @@ public Page<AlcoholResponseDto> getAlcoholV2(
Pageable pageable,
@RequestParam(required = false, name = "searchKeyword")
@Schema(description = "키워드", example = "키워드")
String searchKeyword) {
String searchKeyword,
@RequestParam(required = false, name = "alcoholType")
@Schema(description = "술 타입(선택)", example = "1")
@Positive(message = "술 타입은 1이상의 숫자만 가능합니다.")
Long alcoholType) {
log.info(">>> AlcoholController.getAlcohol");
return alcoholService.getAlcoholV2(pageable, searchKeyword);
return alcoholService.getAlcoholV2(pageable, searchKeyword, alcoholType);
}

@Operation(summary = "[o]술 상세 조회", description = "술 상세 조회 API")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@
public class AlcoholSearchCondition {
@Schema(description = "키워드", example = "키워드")
String searchKeyword;
@Schema(description = "술 종류 PK", example = "1")
Long alcoholType;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,21 @@

import com.bside.bside_311.dto.AlcoholSearchCondition;
import com.bside.bside_311.entity.Alcohol;
import com.bside.bside_311.entity.Post;
import com.bside.bside_311.entity.QAlcohol;
import com.bside.bside_311.entity.QAlcoholType;
import com.bside.bside_311.entity.QUser;
import com.bside.bside_311.entity.YesOrNo;
import com.bside.bside_311.repository.support.Querydsl4RepositorySupport;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import jakarta.persistence.EntityManager;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.util.StringUtils;

import java.util.Optional;
import java.util.function.Function;

import static com.bside.bside_311.entity.QAlcohol.alcohol;
import static com.bside.bside_311.entity.QAlcoholType.alcoholType;
import static com.bside.bside_311.entity.QPost.post;

public class AlcoholRepositoryImpl extends Querydsl4RepositorySupport
implements AlcoholRepositoryCustom {
Expand All @@ -39,14 +33,20 @@ public Page<Alcohol> searchAlcoholPage(AlcoholSearchCondition condition, Pageabl
query -> query.select(alcohol)
.from(alcohol)
.leftJoin(alcoholType).on((alcohol.alcoholType.eq(alcoholType))
.and(alcohol.delYn.eq(YesOrNo.N))
.and(alcoholType.delYn.eq(YesOrNo.N)))
.and(alcohol.delYn.eq(YesOrNo.N))
.and(alcoholType.delYn.eq(YesOrNo.N)))
.where(contentLike(condition.getSearchKeyword()),
alcoholTypeIs(condition.getAlcoholType()),
notDeleted());
return applyPagination(pageable, jpaQueryFactoryJPAQueryFunction
);
}

private BooleanExpression alcoholTypeIs(Long alcoholType) {
return ObjectUtils.isNotEmpty(alcoholType) ? alcohol.alcoholType.id.eq(alcoholType) :
null;
}

private BooleanExpression contentLike(String searchKeyword) {
return StringUtils.hasText(searchKeyword) ? alcohol.name.contains(searchKeyword) : null;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
package com.bside.bside_311.service;

import com.bside.bside_311.component.AlcoholManager;
import com.bside.bside_311.component.AttachManager;
import com.bside.bside_311.dto.AddAlcoholRequestDto;
import com.bside.bside_311.dto.AddAlcoholResponseDto;
import com.bside.bside_311.dto.AlcoholResponseDto;
import com.bside.bside_311.dto.AlcoholSearchCondition;
import com.bside.bside_311.dto.AttachDto;
import com.bside.bside_311.dto.EditAlcoholRequestDto;
import com.bside.bside_311.dto.GetAlcoholResponseDto;
Expand All @@ -14,7 +15,6 @@
import com.bside.bside_311.entity.AlcoholNickname;
import com.bside.bside_311.entity.AlcoholTag;
import com.bside.bside_311.entity.AlcoholType;
import com.bside.bside_311.entity.Attach;
import com.bside.bside_311.entity.AttachType;
import com.bside.bside_311.entity.Tag;
import com.bside.bside_311.entity.YesOrNo;
Expand Down Expand Up @@ -45,6 +45,8 @@
@RequiredArgsConstructor
@Transactional
public class AlcoholService {
private final AlcoholManager alcoholManager;
private final AttachManager attachManager;
private final AlcoholRepository alcoholRepository;
private final TagService tagService;
private final TagRepository tagRepository;
Expand Down Expand Up @@ -189,25 +191,12 @@ public GetAlcoholResponseDto getAlcohol(Long page, Long size, String orderColumn
return GetAlcoholResponseDto.of(alcoholResponseDtos, alcoholsCount);
}

public Page<AlcoholResponseDto> getAlcoholV2(Pageable pageable, String searchKeyword) {
// 술 종류 fetch join
Page<Alcohol> alcohols = alcoholRepository.searchAlcoholPage(AlcoholSearchCondition.builder()
.searchKeyword(
searchKeyword)
.build(),
pageable);
public Page<AlcoholResponseDto> getAlcoholV2(Pageable pageable, String searchKeyword,
Long alcoholType) {
Page<Alcohol> alcohols = alcoholManager.searchAlcohol(pageable, searchKeyword, alcoholType);
List<Long> alcoholNos = alcohols.stream().map(Alcohol::getId).toList();
List<Attach> alcoholAttachList =
attachRepository.findByRefNoInAndAttachTypeIsAndDelYnIs(alcoholNos, AttachType.ALCOHOL,
YesOrNo.N);
Map<Long, List<AttachDto>> aToAMap = new HashMap<>();
for (Attach attach : alcoholAttachList) {
if (!aToAMap.containsKey(attach.getRefNo())) {
aToAMap.put(attach.getRefNo(), new ArrayList<>());
}
List<AttachDto> attachDtos = aToAMap.get(attach.getRefNo());
attachDtos.add(AttachDto.of(attach));
}
Map<Long, List<AttachDto>> aToAMap = attachManager.getAttachInfoMapBykeysAndType(alcoholNos,
AttachType.ALCOHOL);
return alcohols.map(alcohol -> {
List<AttachDto> attachDtos = aToAMap.getOrDefault(alcohol.getId(), new ArrayList<>());
return AlcoholResponseDto.of(alcohol, attachDtos);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,24 @@ void getAlcoholTypeList() throws Exception {

//then
}

@Test
void getAlcoholV2_success() throws Exception {
// given
// when
// then
String queryParameter = "?alcoholType=1&searchKeyword=소주";
mockMvc.perform(get(String.format("/alcohols/v2%s", queryParameter)))
.andExpect(status().isOk());
}

@Test
void getAlcoholV2_fail() throws Exception {
// given
// when
// then
String queryParameter = "?alcoholType=asdf&searchKeyword=소주";
mockMvc.perform(get(String.format("/alcohols/v2%s", queryParameter)))
.andExpect(status().is4xxClientError());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.bside.bside_311.repository;

import com.bside.bside_311.dto.AlcoholSearchCondition;
import com.bside.bside_311.entity.Alcohol;
import com.bside.bside_311.entity.AlcoholType;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.ArrayList;
import java.util.List;

@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class AlcoholRepositoryTest {
@Autowired
AlcoholTypeRepository alcoholTypeRepository;

@Autowired
AlcoholRepository alcoholRepository;

@PersistenceContext
private EntityManager em;

@Test
void findByAlcoholType() {
//given 술타입이 3종류 있다.
// 그리고 술은 한 8개 있음.
// 그중에 3개 정도가 내가 조회하려는 타입임.
//when 술타입으로 조회하면
//then 3개가 조회됨.
List<AlcoholType> alcoholTypeList = dataInitAlcoholType();
List<Alcohol> alcoholList = dataInitAlcohol(alcoholTypeList);

// when.
Page<Alcohol> byAlcoholType =
alcoholRepository.searchAlcoholPage(AlcoholSearchCondition.builder()
.alcoholType(
alcoholTypeList.get(
0).getId())
.build(),
PageRequest.of(0, 10));

// then.
List<Alcohol> content = byAlcoholType.getContent();
content.forEach(System.out::println);
Assertions.assertThat(content.size()).isEqualTo(4);


}

private List<Alcohol> dataInitAlcohol(List<AlcoholType> alcoholTypeList) {
List<Alcohol> alcoholList = new ArrayList<>();
for (int i = 0; i < 10; i++) {
// 술 10개 만들기
// alcoholTypeList 기준.
// 0idx : 4
// 1idx : 3
// 2idx : 3
alcoholList.add(
Alcohol.builder().name("술" + i).description("설명이다" + i)
.alcoholType(alcoholTypeList.get(i % 3)).build());
}
alcoholRepository.saveAll(alcoholList);
em.flush();
em.clear();
return alcoholList;
}

private List<AlcoholType> dataInitAlcoholType() {
List<AlcoholType> alcoholTypeList = new ArrayList<>();
for (int i = 0; i < 3; i++) {
// 알코올 타입 3개 만들기
alcoholTypeList.add(
AlcoholType.builder().name("맥주" + i).description("설명이다" + i).displayOrder(i + 1L)
.build());
}
alcoholTypeRepository.saveAll(alcoholTypeList);
em.flush();
em.clear();


return alcoholTypeList;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@SpringBootTest
@Transactional
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
//@Rollback(false)
class PostRepositoryTest {
@Autowired
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,12 @@
import com.bside.bside_311.entity.UserFollow;
import com.bside.bside_311.entity.YesOrNo;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;

import java.util.List;

@ExtendWith(SpringExtension.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
class UserFollowRepositoryTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,18 @@
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@SpringBootTest
@Transactional
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
//@Rollback(false)
class UserRepositoryTest {
@Autowired
Expand Down

0 comments on commit b17a8a3

Please sign in to comment.