public interface LikesRepository extends JpaRepository<Likes , Integer> {
@Modifying
@Query(value="INSERT INTO likes(imageId, userId, createDate) values(:imageId, :principalId, now())", nativeQuery = true)
int mLikes(@Param("imageId") int imageId , @Param("principalId") int PrincipalId);
@Modifying
@Query(value="DELETE FROM likes WHERE imageId = :imageId AND userId = :principalId ", nativeQuery = true)
int mUnLikes(@Param("imageId")int imageId , @Param("principalId") int PrincipalId);
}
Repository 를 구현합니다.
Likes 모델에서 CreateDate를 넣어줬지만 이것은 Native Query를 사용하면 모델에서 넣어주지 않습니다.
따로 @Query에 now()를 넣어줍시다.
@PostMapping("/api/image/{imageId}/likes")
public ResponseEntity<?> likes(@PathVariable int imageId , @AuthenticationPrincipal PrincipalDetails principalDetails) {
likesService.좋아요(imageId , principalDetails.getUser().getId());
return new ResponseEntity<>(new CMRespDto<>(1, "좋아요 성공", null), HttpStatus.OK);
}
@DeleteMapping("/api/image/{imageId}/likes")
public ResponseEntity<?> unLikes(@PathVariable int imageId , @AuthenticationPrincipal PrincipalDetails principalDetails) {
likesService.좋아요취소(imageId , principalDetails.getUser().getId());
return new ResponseEntity<>(new CMRespDto<>(1, "좋아요취소 성공", null), HttpStatus.OK);
}
따로 LikesController를 만들지 않고 ImageApiController에서 진행하였습니다, 그 이유는
만들어도 되지만 맵핑 주소를 image를 사용할 것이여서 ImageApiController 로 진행합니다.
또한 맵핑에 ${imageId}를 넣을것이기 때문에 @PathVariable 을 선언해줍니다.
@RequiredArgsConstructor
@Service
public class LikesService {
private final LikesRepository likesRepository;
@Transactional
public void 좋아요(int imageId , int principalId ){
likesRepository.mLikes(imageId,principalId);
}
@Transactional
public void 좋아요취소(int imageId , int principalId){
likesRepository.mUnLikes(imageId, principalId);
}
}
단순한 insert , delete 구조이기에 별다른 구조는 없다.
Q. 데이터를 주고받는데 ajax 안만들어도되나요?
A. 우선 포토 게시판 뷰 구현할때 만들어놓은 ajax를 사용해서 뷰 먼저 구현하고
최종적으로 좋아요 구현하기 -4에서 좋아요 누르는 ajax를 구현할 예정.
'Spring > JPA + Security' 카테고리의 다른 글
[Spring Data JPA]좋아요 구현하기 -4 Ajax 연결 후 마무리하기 (0) | 2023.01.13 |
---|---|
[Spring Data JPA] 좋아요 구현하기 -3 좋아요 뷰 렌더링, 카운트 렌더링 (0) | 2023.01.13 |
[Spring Data JPA] 좋아요 구현하기 - 1 모델 만들기 (0) | 2023.01.12 |
[Spring Data JPA] 포토 게시판 페이지 구현하기 -3 JPA 페이징 처리 예제 (0) | 2023.01.12 |
[Spring Data JPA] 포토 게시판 페이지 구현하기 - 2 포토리스트 띄우기 및 Ajax를 통한 뷰 렌더링 (0) | 2023.01.12 |
댓글