ํฐ์คํ ๋ฆฌ ๋ทฐ
JPA Auditing ํ ์ด๋ธ ๋ณ๊ฒฝ ์ฌํญ ํน์ ํ๋์์ ์๋ ๋ฐฉ์ง
hae.company 2023. 10. 6. 17:06JPA 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
- ๋ฐฑ์ค
- error
- PostgreSQL
- sqld
- ์ํฐ๋ ์ฑ๋ฆฐ์ง
- ์ ๋ณด์ฒ๋ฆฌ๊ธฐ์ฌ ์ค๊ธฐ
- oracle
- ์ฝ๋์คํ ์ด์ธ
- ๋ ์
- doit์๊ณ ๋ฆฌ์ฆ์ ๋ฌธ
- yml ๋ถ๋ฆฌ
- ์ฐ๋ถํฌ
- preproject
- Spring
- Stream
- mapper
- Til
- Java
- docker
- mysql ์ค์
- xml
- modifiedAt
- ๋ฐ์ดํฐ๋ฒ ์ด์ค
- JSP
- ๋ค์ด๋๋ฏนํ๋ก๊ทธ๋๋ฐ
- ํ๊ณ
- codestates
- ๋์ปค
- pyinstaller ์ค์น
- VMware
| ์ผ | ์ | ํ | ์ | ๋ชฉ | ๊ธ | ํ |
|---|---|---|---|---|---|---|
| 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 |