λ°μν
Auditing
μν°ν°μ κ³΅ν΅ λ©€λ² λ³μλ€μ μΆμ ν΄λμ€λ‘ λ§λ€κ³ , ν΄λΉ μΆμ ν΄λμ€λ₯Ό μμλ°μ μν°ν°μ 곡ν΅μ μΈ κΈ°λ₯μ μννλλ‘ νλ©° μν°ν°μ μμ±κ³Ό μμ μ κ°μνλ κΈ°λ²
AuditorAware μΈν°νμ΄μ€
- νμ¬ λ‘κ·ΈμΈν μ¬μ©μμ μ 보λ₯Ό λ±λ‘μμ μμ μλ‘ μ§μ νκΈ° μν΄μ
AuditorAware
μΈν°νμ΄μ€λ₯Ό ꡬνν ν΄λμ€ μμ±
public class AuditorAwareImpl implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String userId = "";
if (authentication != null) {
userId = authentication.getName();
}
return Optional.of(userId);
}
Auditing κΈ°λ₯μ μ¬μ©νκΈ° μν΄ AuditConfig νμΌ μμ±
@Configuration
@EnableJpaAuditing
public class AuditConfig {
@Bean
public AuditorAware<String> auditorProvider() {
return new AuditorAwareImpl();
}
}
@EnableJpaAuditing
β JPAμ Auditing κΈ°λ₯μ νμ±νauditorProvider
μ΄λ¦μΌλ‘AuditorAware
μ λΉμΌλ‘ λ±λ‘
BaseTimeEntity, BaseEntity
- λ±λ‘μ λ° μμ μλ₯Ό μ μΈν μκ°κ΄λ ¨ Auditing κΈ°λ₯ μν Entity
@EntityListeners(value = {AuditingEntityListener.class})
@MappedSuperclass
@Getter
@Setter
public abstract class BaseTimeEntity {
@CreatedDate
@Column(updatable = false)
private LocalDateTime reqTIme;
@LastModifiedBy
private LocalDateTime updateTime;
}
- λ±λ‘μ λ° μμ μ, λ±λ‘/μμ μκ°μ λͺ¨λ κ°λ Entity
BaseTimeEntity
μμ@EntityListeners(value = {AuditingEntityListener.class}) @MappedSuperclass @Getter public abstract class BaseEntity extends BaseTimeEntity { @CreatedBy @Column(updatable = false) private String createdBy; @LastModifiedBy private String modifiedBy; }
ν μ€νΈ
public class Member extends BaseEntity { /**/ }
@SpringBootTest
@Transactional
@TestPropertySource(locations = "classpath:application-test.properties")
class MemberTest {
@Autowired
MemberRepository memberRepository;
@PersistenceContext
EntityManager entityManager;
@Test
@WithMockUser(username = "test", roles = "USER")
void Auditing_ν
μ€νΈ() {
Member newMember = new Member();
memberRepository.save(newMember);
entityManager.flush();
entityManager.clear();
Member member = memberRepository.findById(newMember.getId())
.orElseThrow(EntityNotFoundException::new);
System.out.println("register time : " + member.getReqTime());
System.out.println("update time : " + member.getUpdateTime());
System.out.println("create member : " + member.getCreatedBy());
System.out.println("modify member : " + member.getModifiedBy());
}
}
728x90
λ°μν
'μ€νλ§ > μΌνλͺ° νλ‘μ νΈ' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
μν μμ νκΈ° (0) | 2022.11.28 |
---|---|
μ§μ° λ‘λ© (0) | 2022.11.27 |
μμμ± μ μ΄ (0) | 2022.11.26 |
μ°κ΄ κ΄κ³ 맀ν (0) | 2022.11.25 |
νμ΄μ§ κΆν μ€μ νκΈ° (0) | 2022.11.24 |