백엔드/스프링, 스프링부트, JPA, Spring Webflux
[리팩토링] EntityManager → QueryDSL을 이용한 getCategories
Kangjieun11
2022. 12. 22. 23:35
728x90
✅ 이전 버전은..
- 앞서 entitymanager를 직접 불러와 사용하는것
- 레포지토리르 2개나 만들어 사용한것 (서비스에 2개의 의존 레포지토리가 생겼다)
https://jie0025.tistory.com/345
예전에 스터디하면서 정리해놓은 글이 있어 해당 사용방법을 참고했다.
https://jie0025.tistory.com/254
✅ QueryDSL을 이용한 리팩토링
💻 CategoryRepositoryImpl
package com.FlagHome.backend.v1.category.repository;
import com.FlagHome.backend.v1.category.entity.Category;
import com.FlagHome.backend.v1.category.entity.QCategory;
import com.querydsl.jpa.impl.JPAQueryFactory;
import lombok.RequiredArgsConstructor;
import java.util.List;
@RequiredArgsConstructor
public class CategoryRepositoryImpl implements CategoryRepositoryCustom{
private final JPAQueryFactory queryFactory;
@Override
public List<Category> findAll(){
QCategory category = QCategory.category;
List<Category> result = queryFactory
.select(category)
.from(category)
.where(category.parent.isNull())
.fetch();
return result;
}
}
💻 CategoryRepositoryCustom
package com.FlagHome.backend.v1.category.repository;
import com.FlagHome.backend.v1.category.entity.Category;
import java.util.List;
public interface CategoryRepositoryCustom {
List<Category> findAll();
}
💻 CategoryRepository
package com.FlagHome.backend.v1.category.repository;
import com.FlagHome.backend.v1.category.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoryRepository extends JpaRepository<Category,Long>, CategoryRepositoryCustom {
}
💻 CategoryResultDto
package com.FlagHome.backend.v1.category.dto;
import com.FlagHome.backend.v1.category.entity.Category;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.util.List;
import java.util.stream.Collectors;
@Getter
@AllArgsConstructor
@NoArgsConstructor
public class CategoryResultDto {
private Long id;
private String name;
private Long depth;
private List<CategoryResultDto> children;
public static CategoryResultDto of(Category category) {
return new CategoryResultDto(
category.getId(),
category.getName(),
category.getCategoryDepth(),
category.getChildren().stream().map(CategoryResultDto::of).collect(Collectors.toList())
);
}
}
💻 CategoryService
@Service
@RequiredArgsConstructor
public class CategoryService {
private CategoryRepository categoryRepository;
@Transactional
public List<CategoryResultDto> getCategories () {
List<CategoryResultDto> categories = categoryRepository
.findAll().stream().map(CategoryResultDto::of)
.collect(Collectors.toList());
return categories;
}
}
✅ 동작확인
이전과 정확하게 똑같이 동작하는것을 확인했다.