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

fix: 좋아요 데이터 동시성 제어 #107

Merged
merged 2 commits into from
Nov 14, 2024
Merged
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
8 changes: 7 additions & 1 deletion src/main/java/com/potatocake/everymoment/entity/Like.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,18 @@
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;
import jakarta.persistence.UniqueConstraint;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Table(name = "likes")
@Table(
name = "likes",
uniqueConstraints = {
@UniqueConstraint(columnNames = {"member_id", "diary_id"})
}
)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Getter
@Entity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,18 @@

import com.potatocake.everymoment.entity.Diary;
import com.potatocake.everymoment.entity.Like;
import jakarta.persistence.LockModeType;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface LikeRepository extends JpaRepository<Like, Long> {

Optional<Like> findByMemberIdAndDiaryId(Long memberId, Long diaryId);
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT l FROM Like l WHERE l.member.id = :memberId AND l.diary.id = :diaryId")
Optional<Like> findByMemberIdAndDiaryIdWithLock(@Param("memberId") Long memberId, @Param("diaryId") Long diaryId);

Long countByDiary(Diary diary);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void toggleLike(Long memberId, Long diaryId) {
Member member = memberRepository.findById(memberId)
.orElseThrow(() -> new GlobalException(ErrorCode.MEMBER_NOT_FOUND));

Optional<Like> existingLike = likeRepository.findByMemberIdAndDiaryId(memberId, diaryId);
Optional<Like> existingLike = likeRepository.findByMemberIdAndDiaryIdWithLock(memberId, diaryId);

if (existingLike.isPresent()) {
// 이미 좋아요가 존재하면 삭제 (좋아요 취소)
Expand Down