[Spring] 비관적 락을 이용한 songCnt 업데이트 문제 #196
Answered
by
PFCJeong
DoohyunHwang97
asked this question in
Q&A
-
@Transactional
override fun addSong(userId: Long, customPlaylistId: Long, songId: Long): CustomPlaylistBrief {
val customPlaylist = customPlaylistRepository.findById(customPlaylistId).orElseThrow { CustomPlaylistNotFoundException() }
if (customPlaylist.userId != userId) throw CustomPlaylistNotFoundException()
val songToAdd = songRepository.findById(songId).orElseThrow { SongNotFoundException() }
val songsInCustomPlaylist = customPlaylist.songs.map { it.song }
if (!songsInCustomPlaylist.contains(songToAdd)) {
customPlaylist.songs.add(CustomPlaylistSongEntity(customPlaylist = customPlaylist, song = songToAdd))
// songCnt 업데이트
customPlaylistRepository.increaseSongCnt(customPlaylistId)
}
return CustomPlaylistBrief(id = customPlaylistId, title = customPlaylist.title, songCnt = customPlaylist.songCnt)
} interface CustomPlaylistRepository : JpaRepository<CustomPlaylistEntity, Long> {
fun findAllByUserId(userId: Long): List<CustomPlaylistEntity>
@Lock(value = LockModeType.PESSIMISTIC_WRITE)
@Query("UPDATE custom_playlists c SET c.songCnt = c.songCnt + 1 WHERE c.id = :playlistID")
fun increaseSongCnt(playlistID: Long)
} 테스트 코드는 아래와 같이 트랜잭션 템플릿을 이용했습니다. @Test
fun `커스텀 플레이리스트에 곡 추가시, songCnt가 올라가고 연결 테이블의 row가 생성된다`() {
TransactionTemplate(txManager).executeWithoutResult {
val created = customPlaylistService.create(userId = 1L)
customPlaylistService.addSong(
userId = 1L,
customPlaylistId = created.id,
songId = 1L
)
// songCnt 컬럼 체크
val customPlaylistEntity = customPlaylistRepository.findById(created.id).get()
assertThat(customPlaylistEntity.songCnt).isEqualTo(1)
// customPlaylistSong 연결 테이블 체크
val customPlaylist = customPlaylistService.get(userId = 1L, customPlaylistId = created.id)
assertThat(customPlaylist.songs.size).isEqualTo(1)
assertThat(customPlaylist.songs.first().id).isEqualTo(1L)
}
} 업데이트시에 아래와 같은 문제가 발생했는데 무엇이 잘못된지 모르겠어서 질문드립니다 ㅠ org.springframework.dao.InvalidDataAccessApiUsageException: Expecting a SELECT query : 감사합니다 |
Beta Was this translation helpful? Give feedback.
Answered by
PFCJeong
Nov 5, 2023
Replies: 2 comments 5 replies
-
답변은 아니지만, 4번 구현할 때 @transactional을 쓰지 말라고 하셔서 고민중이었는데, 혹시 두현님처럼 구현하는 방식도 상관이 없는건가요..? |
Beta Was this translation helpful? Give feedback.
2 replies
-
안녕하세요 |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
DoohyunHwang97
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
안녕하세요
@Lock(value = LockModeType.PESSIMISTIC_WRITE)
제거하고@Modifying
로 시도해보시면 좋을 것 같습니다.