반응형

Likes.class
-mysql과 마리아db는 like가 키워드라서 Likes란 이름으로 짓는다.
-한 유저가 특정 이미지를 중복으로 like할 수 없기때문에 @Table - uniqueConstraints 설정을 해준다.
- Likes와 Images는 n:1 관계다 
- 또한  likes와 User 도 n:1관계다 

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Data
@Entity
@Table(
        uniqueConstraints = {
                @UniqueConstraint(
                        name = "likes_uk",
                        columnNames = {"imageId", "userId"} 
                )
        }
)
public class Likes { //N
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @JoinColumn(name="imageId")
    @ManyToOne //기본 패치전략은 EAGER
    private Image image; // 1

    @JsonIgnoreProperties({"images"})
    @JoinColumn(name="userId")
    @ManyToOne
    private User user; //1

    private LocalDateTime createDate;

    @PrePersist
    public void createDate(){
        this.createDate = LocalDateTime.now();
    }
}

 

LikesRepository
- likes 테이블에 이미지 아이디와 로그인한 유저아이디, 그리고 현재시간을 넣어주는 쿼리작성

public interface LikesRepository extends JpaRepository<Likes, Integer> {

    @Modifying
    @Query(value = "INSERT INTO likes(imageId, userId, createDate) VALUES (:imageId, :principalId, now())", nativeQuery = true)
    int mLikes(int imageId, int principalId);


    @Modifying
    @Query(value = "DELETE FROM likes WHERE imageId =:imageId AND userId =:principalId", nativeQuery = true)
    int mUnLikes(int imageId, int principalId);
}

 

LikesService

@RequiredArgsConstructor
@Service
public class LikesService {

    private final LikesRepository likesRepository;

    @Transactional
    public void like(int imageId, int principalId){
        likesRepository.mLikes(imageId, principalId);
    }

    @Transactional
    public void unlike(int imageId, int principalId){
        likesRepository.mUnLikes(imageId, principalId);
    }

}


ImageApiController

@RequiredArgsConstructor
@RestController
public class ImageApiController {

    private final ImageService imageService;
    private final LikesService likesService;

   ...

    //이미지 좋아요
    @PostMapping("/api/image/{imageId}/likes")
    public ResponseEntity<?>likes(@PathVariable int imageId, @AuthenticationPrincipal PrincipalDetails principalDetails){

        likesService.like(imageId, principalDetails.getUser().getId());

        return new ResponseEntity<>(new CMRespDto<>(1, "좋아요성공", null), HttpStatus.CREATED);

    }

    //이미지 좋아요 취소
    @DeleteMapping("/api/image/{imageId}/likes")
    public ResponseEntity<?>unLikes(@PathVariable int imageId, @AuthenticationPrincipal PrincipalDetails principalDetails){

        likesService.unlike(imageId, principalDetails.getUser().getId());

        return new ResponseEntity<>(new CMRespDto<>(1, "좋아요 취소성공", null), HttpStatus.OK);

    }
}

 

+ Recent posts