Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FEAT] 쿼리 개선 1차 작업 #190

Open
wants to merge 6 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion src/main/java/com/gam/api/ApiApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;

@SpringBootApplication
public class ApiApplication {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ ResponseEntity<ApiResponse> getPortfolio(
@AuthenticationPrincipal GamUserDetails userDetails,
@PathVariable Long userId)
{
val response = userService.getPortfolio(userDetails.getId(), userId);
val response = userService.getPortfolio(userDetails.getUser(), userId);
return ResponseEntity.ok(ApiResponse.success(ResponseMessage.SUCCESS_GET_PROTFOLIO_LIST.getMessage(), response));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
@Getter
public class GamUserDetails implements UserDetails {

// TODO: User 객체 이전 이후 삭제 필요
private final Long id;
private final User user;
private final String username;
private final String authUserId;
private List<GrantedAuthority> authorities;
Expand All @@ -21,6 +23,11 @@ public List<GrantedAuthority> getAuthorities() {
return authorities;
}

public User getUser() {
return user;
}

// TODO: User 객체 이전 이후 삭제 필요
public Long getId() {
return id;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> getUserById(Long userId);
boolean existsByUserName(String userName);

@Query("SELECT u FROM User u JOIN FETCH u.works WHERE u.id = :userId")
Optional<User> getUserByIdWithWorks(@Param("userId") Long userId);

List<User> findByUserStatusAndFirstWorkIdIsNotNullOrderByScrapCountDesc(UserStatus userStatus);

@Query(value = "SELECT u FROM User u WHERE LOWER(u.userName) LIKE %:keyword% ORDER BY u.createdAt DESC")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.gam.api.domain.user.repository;

import com.gam.api.domain.user.entity.User;
import com.gam.api.domain.user.entity.UserScrap;
import com.gam.api.domain.user.dto.query.UserScrapQueryDto;
import org.springframework.data.jpa.repository.JpaRepository;
Expand All @@ -9,8 +10,11 @@
import org.springframework.data.repository.query.Param;

public interface UserScrapRepository extends JpaRepository<UserScrap, Long> {
List<UserScrap> findUserScrapsByUserId(Long userId);
UserScrap findByUser_idAndTargetId(Long userId, Long targetId);

UserScrap findByUserAndTargetId(User user, Long targetId);

@Query("SELECT DISTINCT NEW com.gam.api.domain.user.dto.query.UserScrapQueryDto(us.id, us.modifiedAt, us.targetId) "+
"FROM UserScrap us " +
"LEFT JOIN FETCH User tu ON us.targetId = tu.id " +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.persistence.EntityNotFoundException;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -41,6 +40,7 @@ public UserDetails loadUserByUsername(String userId) {

return GamUserDetails.builder()
.id(user.getId())
.user(user)
.authUserId(authUserId)
.username(user.getUserName())
.authorities(authorities)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import com.gam.api.domain.user.dto.response.UserResponseDTO;
import com.gam.api.domain.user.dto.response.UserScrapsResponseDTO;
import com.gam.api.domain.user.dto.response.SearchUserWorkDTO;
import com.gam.api.domain.user.entity.User;
import com.gam.api.domain.work.dto.response.WorkPortfolioGetResponseDTO;
import com.gam.api.domain.work.dto.response.WorkPortfolioListResponseDTO;

Expand Down Expand Up @@ -32,7 +33,7 @@ public interface UserService {
List<UserScrapsResponseDTO> getUserScraps(Long userId);
List<UserResponseDTO> getPopularDesigners(Long userId);
WorkPortfolioListResponseDTO getMyPortfolio(Long userId);
WorkPortfolioGetResponseDTO getPortfolio(Long requestUserId, Long userId);
WorkPortfolioGetResponseDTO getPortfolio(User requestUser, Long userId);
List<UserDiscoveryResponseDTO> getDiscoveryUsers(Long userId, int[] tags);
void updateInstagramLink(Long userId, UserUpdateLinkRequestDTO request);
void updateBehanceLink(Long userId, UserUpdateLinkRequestDTO request);
Expand Down
33 changes: 24 additions & 9 deletions src/main/java/com/gam/api/domain/user/service/UserServiceImpl.java
Original file line number Diff line number Diff line change
Expand Up @@ -264,18 +264,19 @@ public WorkPortfolioListResponseDTO getMyPortfolio(Long userId) {

@Transactional
@Override
public WorkPortfolioGetResponseDTO getPortfolio(Long requestUserId, Long userId) {
val requestUser = findUser(requestUserId);
val user = findUser(userId);
public WorkPortfolioGetResponseDTO getPortfolio(User requestUser, Long userId) {
val user = findUserWithWorks(userId);
user.setViewCount(user.getViewCount() + 1);
val works = getUserPortfolios(userId);
works.forEach(w -> w.viewCountUp());
val works = refineWorkList(user.getWorks());

val workIds = works.stream()
.map(Work::getId)
.toList();

val scrapList = requestUser.getUserScraps().stream()
.map(UserScrap::getTargetId)
.toList();
workRepository.updateWorksViewCount(workIds);

val isScraped = scrapList.contains(user.getId());
val userScrap = userScrapRepository.findByUserAndTargetId(requestUser, user.getId());
val isScraped = Objects.isNull(userScrap);

return WorkPortfolioGetResponseDTO.of(isScraped, user, works);
}
Expand Down Expand Up @@ -365,11 +366,25 @@ private List<Work> getUserPortfolios(Long userId) {
return works;
}

private List<Work> refineWorkList(List<Work> works) {
return works
.stream()
.filter(Work::isActive)
.sorted(Comparator.comparing(Work::isFirst, Comparator.reverseOrder())
.thenComparing(Comparator.comparing(Work::getCreatedAt).reversed()))
.collect(Collectors.toList());
}

private User findUser(Long userId) {
return userRepository.findById(userId)
.orElseThrow(() -> new EntityNotFoundException(ExceptionMessage.NOT_FOUND_USER.getMessage()));
}

private User findUserWithWorks(Long userId) {
return userRepository.getUserByIdWithWorks(userId)
.orElseThrow(() -> new EntityNotFoundException(ExceptionMessage.NOT_FOUND_USER.getMessage()));
}


private void createUserScrap(User user, Long targetId, User targetUser){
userScrapRepository.save(UserScrap.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package com.gam.api.domain.work.repository;

import com.gam.api.domain.work.entity.Work;
import io.lettuce.core.dynamic.annotation.Param;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.util.List;
Expand All @@ -18,4 +20,8 @@ public interface WorkRepository extends JpaRepository<Work, Long> {
@Query(value = "SELECT w FROM Work w WHERE LOWER(w.title) LIKE LOWER(CONCAT('%', :keyword, '%')) ORDER BY w.createdAt DESC")
List<Work> findByKeyword(String keyword);
Optional<Work> findFirstByUserIdAndIsActiveOrderByCreatedAtDesc(Long userId, boolean isActive);

@Modifying
@Query("UPDATE Work w SET w.viewCount = w.viewCount + 1 WHERE w.id IN :ids")
void updateWorksViewCount(@Param("ids") List<Long> ids);
}
Loading