Spring Data JPA 의 Audit 기능 감사 데이터베이스 변경
1 데이터베이스 감사
데이터베이스 감사 란 데이터베이스 에 기록 변경 이 있 을 때 데이터베이스 의 변경 시간 과 변경 자 등 을 기록 할 수 있 기 때문에 나중에 문제 가 생기 면 거 슬러 올 라 가 책임 을 묻 는 것 도 비교적 편리 하 다 는 것 을 말한다.감사 표 기록 의 변경 은 두 가지 방식 으로 할 수 있다.하 나 는 감사 표를 만들어 기록 에 사용 하 는 것 이 고 다른 하 나 는 데이터 베이스 에 필드 를 추가 하 는 것 이다.본문 에서 토론 한 것 은 두 번 째 방안 이다.
그러면 어떻게 새로 추가,수정,삭제 할 때 기록 을 동시에 추가 합 니까?표 마다 따로 기록 하면 코드 가 지루 해 보인다.더 좋 은 방법 은 절단면 이나 사건 감청 을 하고 데이터 가 변 경 될 때 통일 적 으로 기록 하 는 것 이다.
2 Spring Data JPA 감사
Spring Data JPA
우리 에 게 편리 한Audit
기능 을 제공 하고 네 개의 주 해 를 통 해 필드 를 표시 합 니 다.(1)@CreatedBy:작성 자
(2)@CreatedDate:생 성 시간
(3)@LastModified By:마지막 수정 자
(4)@LastModified 날짜:마지막 수정 시간
이제 어떻게 사용 하 는 지 봅 시다.
2.1 프로젝트 준비
Docker
시작PostgreSQL
데이터베이스:
docker run -itd \
--name pkslow-postgres \
-e POSTGRES_DB=pkslow \
-e POSTGRES_USER=pkslow \
-e POSTGRES_PASSWORD=pkslow \
-e PGDATA=/var/lib/postgresql/data/pgdata \
-p 5432:5432 \
postgres:10
관련 의존 도입:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Security
필요 한 것 이 아 닙 니 다.사용자 이름 을 가 져 오 는 데 사용 합 니 다.설정 한 사용 자 는:
spring.security.user.name=pkslow
spring.security.user.password=123456
2.2 실체 부모 클래스 만 들 기사실 부 류 는 필수 가 아 닙 니 다.모든 생각
Audit
의 실체 류 를 설정 할 수 있 습 니 다.그러나 귀 찮 습 니 다.부 류 를 만 들 고 감사 하고 싶 은 자 류 를 계승 하 는 것 이 좋 습 니 다.
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class Auditable<U> {
@CreatedBy
@Column(name = "created_by")
private U createdBy;
@CreatedDate
@Column(name = "created_date")
private Date createdDate;
@LastModifiedBy
@Column(name = "last_modified_by")
private U lastModifiedBy;
@LastModifiedDate
@Column(name = "last_modified_date")
private Date lastModifiedDate;
// getter
//setter
}
@MappedSuperclass
다른 하위 실체 류 가 관련 필드 와 속성 을 계승 할 수 있 습 니 다.@EntityListeners
감청 류 를 설정 하면
와
를 리 셋 처리 합 니 다.부류 가 생기 면 자 류 는 간단 해진 다.
@Entity
@Table(name = "pkslow_users")
public class User extends Auditable<String> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
private String name;
private String email;
private String country;
private String website;
//getter setter
}
2.3 이름 가 져 오 는 방법데 이 터 는 항상 수 정 됩 니 다.우 리 는 수 정 된 사람의 이름 을 가 져 오 는 인 터 페 이 스 를 제공 해 야 합 니 다.설정 은 다음 과 같 습 니 다.
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class JpaAuditingConfiguration {
@Bean
public AuditorAware<String> auditorProvider() {
return () -> {
String username = "system";
SecurityContext context = SecurityContextHolder.getContext();
if (context != null) {
Authentication authentication = context.getAuthentication();
if (authentication != null) {
username = authentication.getName();
}
}
String result = username;
return Optional.ofNullable(result);
};
}
}
이 설정 은Spring Security
의Context
를 통 해 로그 인 사용자 의 이름 을 가 져 옵 니 다.요청 헤더 의 한 필드 를 가 져 오 는 등 다른 방안 이 있 습 니 다.주의 주해
@EnableJpaAuditing
감사 기능 이 시작 되 었 습 니 다.2.4 테스트
우 리 는
Controller
를 통 해 데 이 터 를 추가 하여 어떤 효과 가 있 는 지 봅 시다.
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@PostMapping
public User save(@RequestBody User user) {
return userRepository.save(user);
}
}
curl
명령 을 통 해 다음 과 같이 테스트 합 니 다:
$ curl 'http://localhost:8088/user' -X POST \
> -H 'Content-Type: application/json' \
> -H 'Authorization:Basic cGtzbG93OjEyMzQ1Ng==' \
> -d '{
> "name":"larry",
> "email":"[email protected]",
> "country":"China",
> "website":"www.pkslow.com"
> }'
{"createdBy":"pkslow","createdDate":"2021-01-15T15:08:47.035+0000","lastModifiedBy":"pkslow","lastModifiedDate":"2021-01-15T15:08:47.035+0000","userId":7,"name":"larry","email":"[email protected]","country":"China","website":www.pkslow.com}
데이터 베 이 스 를 보면 감사 기록 이 생 성 되 었 습 니 다.3 총화
코드 확인:https://github.com/LarryDpk/pkslow-samples
Spring Data JPA 의 Audit 기능 감사 데이터베이스 변경 에 관 한 이 글 은 여기까지 소개 되 었 습 니 다.더 많은 Spring Data JPA 감사 데이터베이스 변경 내용 은 우리 의 이전 글 을 검색 하거나 아래 의 관련 글 을 계속 조회 하 시기 바 랍 니 다.앞으로 도 많은 응원 부 탁 드 리 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
[MeU] Hashtag 기능 개발➡️ 기존 Tag 테이블에 존재하지 않는 해시태그라면 Tag , tagPostMapping 테이블에 모두 추가 ➡️ 기존에 존재하는 해시태그라면, tagPostMapping 테이블에만 추가 이후에 개발할 태그 기반 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.