ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฐ˜์‘ํ˜•

JPA Auditing?

์Šคํ”„๋ง JPA๋ฅผ ์‚ฌ์šฉํ•ด DB์— ๋ฐ์ดํ„ฐ๋ฅผ ์ƒ์„ฑ, ์ˆ˜์ • ์‹œ๊ฐ„์„ ๋„ฃ์„๋•Œ ์‚ฌ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•œ ๋ฐฉ๋ฒ•์ด๋‹ค. ์ด ๊ธฐ๋Šฅ์„ ์‚ฌ์šฉํ•˜์—ฌ ๊ด€๋ฆฌ๋ฅผ ํ•˜๋˜ ์ค‘ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•˜์˜€๋‹ค. 

 

@entity
@EntityListeners(AuditingEntityListener.class) 
public class Post {

		@id
		private Long id;

		private String title;

		private String content;

		private String viewCount;

		private String createdAt;
	
		@CreatedDate
		@Column(updatable = false)
		private LocalDateTime createdAt;

		@LastModifiedDate
		private LocalDateTime modifiedAt;

}

์œ„์™€ ๊ฐ™์€ ์ƒํ™ฉ์—์„œ Post ํด๋ž˜์Šค๋ฅผ ์กฐํšŒํ•˜๋Š” ๋กœ์ง์„ ์ž‘์„ฑํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•ด๋ณด์ž.

 

public class PostService {

    public Post getPost(Long id) {
        Post post = postRepository.findById(id).get();
        post.setViewCount(post.getViewCount + 1);
        
        return post;
    }
}

Post๋ฅผ ์กฐํšŒํ• ๋•Œ๋งˆ๋‹ค viewCount๋ฅผ +1 ์˜ฌ๋ ค์ฃผ๊ณ  ์ปจํŠธ๋กค๋Ÿฌ์— ์ „๋‹ฌํ•˜๋Š” ๋ฐฉ์‹์˜ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง์„ ๊ตฌ์„ฑํ•˜์˜€๋Š”๋ฐ ์ด๋ ‡๊ฒŒ ๋œ๋‹ค๋ฉด Post์˜ viewCount๊ฐ€ ๋ณ€๊ฒฝ๋˜์—ˆ๊ธฐ๋•Œ๋ฌธ์— JPA๋Š” update ์ฟผ๋ฆฌ๊ฐ€ ๋‚ ๋ผ๊ฐ€๋Š” ์‹œ์ ์— ์ž๋™์œผ๋กœ modifiedAt๋„ ๊ฐ™์ด ์—…๋ฐ์ดํŠธํ•œ๋‹ค.

 

์ฆ‰, Get์š”์ฒญ์ด ๋ ๋•Œ๋งˆ๋‹ค modifiedAt์ด ์ˆ˜์ •๋˜๊ฒŒ ๋œ๋‹ค.

 

ํ•ด๊ฒฐ๋ฐฉ๋ฒ•

ํ•ด๊ฒฐ๋ฐฉ๋ฒ•์€ ์—ฌ๋Ÿฌ๊ฐ€์ง€๊ฐ€ ์žˆ๊ฒ ์ง€๋งŒ ๋‚˜๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฐฉ๋ฒ•์œผ๋กœ ํ•ด๊ฒฐํ•˜์˜€๋‹ค.

 

๋ฐฉ๋ฒ•์€ PostRepository์— JPQL์„ ์ด์šฉํ•ด์„œ ์ˆ˜๋™์œผ๋กœ ๋ฉ”์„œ๋“œ๋ฅผ ๋“ฑ๋ก์‹œ์ผœ์ฃผ๋Š” ๊ฒƒ์ด๋‹ค.

public interface PostRepository extends JpaRepository<Post, Long> {

    @Modifying
    @Query("update Post p set p.viewCount = :viewCount where p.id = :id")
    int updateViewCount(@Param("viewCount") Long viewCount, @Param("id") Long id);

}

๊ทธ๋ฆฌ๊ณ  PostService๋ฅผ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ˆ˜์ •ํ•ด์ค€๋‹ค.

public class PostService {

    public Post getPost(Long id) {
        Post post = postRepository.findById(id).get();
	      
		postRepository.updateViewCount(post.getViewCount() + 1, post.getId())  
			        
        return post;
    }
}

 

์ด๋ ‡๊ฒŒ ์ž‘์„ฑํ•œ ์ดํ›„์— ํ…Œ์ŠคํŠธ๋ฅผ ์ง„ํ–‰ํ•ด๋ณด๋ฉด ๋”์ด์ƒ ์กฐํšŒ์‹œ์— modifiedAt์ด ๋ณ€๊ฒฝ๋˜์ง€ ์•Š๋Š”๋‹ค.

 

๋ฐ˜์‘ํ˜•
๋ฐ˜์‘ํ˜•
๊ณต์ง€์‚ฌํ•ญ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€
Total
Today
Yesterday
๋งํฌ
ยซ   2026/01   ยป
์ผ ์›” ํ™” ์ˆ˜ ๋ชฉ ๊ธˆ ํ† 
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
๊ธ€ ๋ณด๊ด€ํ•จ