후라이

[Web 게시판] 게시글 관리 설계 | 게시글 조회수 카운팅 본문

Spring/웹 게시판

[Web 게시판] 게시글 관리 설계 | 게시글 조회수 카운팅

힐안 2025. 1. 30. 19:52
개발 환경
SpringBoot 3.4.1
Gradle - Groovy
JPA(Spring Data JPA)
Spring Security
Lombok
thymeleaf
DB : MySQL

 

https://github.com/gmlfks/board

 

GitHub - gmlfks/board: inital commit

inital commit. Contribute to gmlfks/board development by creating an account on GitHub.

github.com

 

조회수 증가 쿼리

 

@Entity
@Getter @Setter
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "post_id")
    private Long id;

    private String title;
    private String content;
    private String writer;
    private int view;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

}

 

 

여기서 view는 게시글의 조회수를 의미한다.

이 조회수를 count해서 방문될 때마다 조회수가 증가되도록 설계한다.

 

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {
    @Transactional
    @Modifying
    @Query("update Post p set p.view = p.view + 1 where p.id = :id")
    int updateView(Long id);
 }

 

우선 PostRepository에서

직접 JPQL(Java Persistance Query Language)을 사용하여 조회수(view) 필드를 증가시키는 업데이트 쿼리를 작성한다.

Post 엔티티의 id 속성을 찾아 view 값을 +1 증가시키게 된다.

 

@Modifying : update, delete 같은 변경 쿼리를 수행할 때 필수적이다.

이 어노테이션을 추가하지 않으면 @Query는 기본적으로 SELECT 쿼리로 인식하기 때문에 실행 시 오류가 발생할 수 있다.

 

 

@Transactional
    public int updateView(Long post_id) {
        return postRepository.updateView(post_id);
    }

 

위 코드는 PostService 코드이다.

그냥 Post id를 인자로 넘겨 repository에서 구현한 조회수 증가 쿼리 메서드를 호출하면 된다.