Skip to content

Commit

Permalink
Merge pull request #107 from kakao-tech-campus-2nd-step3/feature/106-โ€ฆ
Browse files Browse the repository at this point in the history
โ€ฆlike-concurrency

fix: ์ข‹์•„์š” ๋ฐ์ดํ„ฐ ๋™์‹œ์„ฑ ์ œ์–ด
  • Loading branch information
peeerr authored Nov 14, 2024
2 parents d52c56c + f2ccd6e commit 8a31893
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
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

0 comments on commit 8a31893

Please sign in to comment.