Error Logs๐Ÿพ

JPA Auditing ํ…Œ์ด๋ธ” ๋ณ€๊ฒฝ ์‚ฌํ•ญ ํŠน์ • ํ•„๋“œ์—์„œ ์ž‘๋™ ๋ฐฉ์ง€

hae02y 2023. 10. 6. 17:06
๋ฐ˜์‘ํ˜•

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์ด ๋ณ€๊ฒฝ๋˜์ง€ ์•Š๋Š”๋‹ค.

 

๋ฐ˜์‘ํ˜•