728x90
어제는 랜덤 물품을 유저에게 보여줬다면 오늘은 중복된 물품을 주지 않도록 로직을 짰다.
User와 Rating 테이블 간 다대다 관계여서 중간테이블(userRatingRelationRepository)을 만든 후 진행했다.
RatingService
@Transactional
public ApiResponse<RatingResponseDto> randomRatingGoods(Long userId) {
Set<Long> UserRatedGoods = userRatingRelationRepository.findUserCheckedGoodsByUserId(userId);
Rating rating = ratingRepository.findRandomRatingWithCountLessThanOrEqual7(UserRatedGoods);
User user = userHelper.getUser(userId);
Goods goods = rating.getGoods();
Image image = rating.getImage();
userRatingRelationRepository.save(new UserRatingRelation(user, rating));
return new ApiResponse<>(true, new RatingResponseDto(goods, image.getImageUrl()), null);
}
UserRatingRepositoryCustomImpl
@RequiredArgsConstructor
public class UserRatingRepositoryCustomImpl implements UserRatingRepositoryCustom{
private final JPAQueryFactory queryFactory;
@Override
public Set<Long> findUserCheckedGoodsByUserId(Long userId) {
QUserRatingRelation qUserRatingRelation = QUserRatingRelation.userRatingRelation;
// 조회가 빠른 Set을 사용
Set<Long> userCheckedGoods = new HashSet<>(queryFactory.select(qUserRatingRelation.rating.ratingId)
.from(qUserRatingRelation)
.where(qUserRatingRelation.user.userId.eq(userId))
.fetch());
if (userCheckedGoods.isEmpty()) {
userCheckedGoods.add(0L); // 첫 평가시 nullException 방지를 위해 0을 추가
}
return userCheckedGoods;
}
}
이후, 이 전글에서 작성한 findRandomRatingWithCountLessThanOrEqual7()메서드에 파라미터 값으로
Set<Long> UserRatedGoods를 전해준 후,
List<Long> ids 값에서 제거해줬다.(ids.removeAll(UserRatedGoods);)
'Springboot' 카테고리의 다른 글
[Springboot] Client-Server 구조 정리 (0) | 2025.03.26 |
---|---|
[Springboot] JWT 0.15.2 (0) | 2024.06.22 |
[Springboot] QueryDSL (0) | 2023.08.08 |
[SpringBoot] Redis Caching (0) | 2023.08.06 |
[Springboot] S3에 이미지 올리기 (0) | 2023.08.01 |