728x90
1. 내일배움캠프 Sping
오늘은 팀 프로젝트를 하였습니다.
2. 김영한의 스프링 기본편
3. 스프링 숙련 프로젝트
오늘은 유저 부분이 완료되어 게시글 부분을 수정하고 좋아요 기능을 추가하였습니다.
https://github.com/KJG04/sparta-news-feed
GitHub - KJG04/sparta-news-feed
Contribute to KJG04/sparta-news-feed development by creating an account on GitHub.
github.com
BoardsLikeContorller
@RestController
@RequestMapping("/boardslike")
@RequiredArgsConstructor
public class BoardsLikeContorller {
private final BoardsLikeService boardsLikeService;
@PostMapping("/{boardId}")
public BoardsLikeResponseDto boardsLike(@PathVariable("boardId") Long boardId, User user) {
return boardsLikeService.boardsLike(boardId, user);
}
}
BoardsLikeService
@Service
@RequiredArgsConstructor
public class BoardsLikeService {
private final BoardsLikeRepository boardsLikeRepository;
private final BoardsRepository boardsRepository;
@Transactional
public BoardsLikeResponseDto boardsLike(Long boardId, User user) {
BoardsLike boardsLike = boardsLikeRepository.findByBoardIdAndUserId(boardId, user.getUserId());
// 처음 좋아요를 누르는 경우 생성을 하고, 만약 전에 누른적이 있다면 상태를 변경합니다.
if (boardsLike == null) {
BoardsLike newboardsLike = new BoardsLike(user.getUserId(), boardId, true);
BoardsLike saveBoardsLike = boardsLikeRepository.save(newboardsLike);
return new BoardsLikeResponseDto(saveBoardsLike);
} else {
if(boardsLike.getLikeState()) {
return new BoardsLikeResponseDto(boardsLike.update());
} else{
return new BoardsLikeResponseDto(boardsLike.update());
}
}
}
}
좋아요 기능은 만약 처음 누르는 경우라면 테이블에 새로 추가를 하고, 전에 누른적이 있다면 update를 통해 true를 false로 혹은 false를 true로 변경해주었습니다.
BoardsLike
@Getter
@Entity
@NoArgsConstructor
public class BoardsLike extends BaseEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long boardsLikeId;
@Column(name = "userId", nullable = false)
private Long userId;
@Column(name = "likeState", nullable = false)
private Boolean likeState;
@Column(name = "boardId", nullable = false)
private Long boardId;
public BoardsLike(Long userId, Long boardId, boolean likeState) {
this.userId = userId;
this.boardId = boardId;
this.likeState = likeState;
}
public BoardsLike update() {
likeState = !likeState;
return this;
}
}
728x90
'TIL' 카테고리의 다른 글
20240905_TIL (0) | 2024.09.05 |
---|---|
20240904_TIL (0) | 2024.09.05 |
20240902_TIL (2) | 2024.09.03 |
20240826_TIL (0) | 2024.08.27 |
20240816_TIL (0) | 2024.08.19 |