• Home
  • About
    • Mayaul photo

      Mayaul

      hello woooooorld.

    • Learn More
    • Facebook
    • LinkedIn
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

hibernate envers 사용하기

19 Apr 2020

Reading time ~1 minute

들어 가면서

  • JPA 를 사용을 하면서, entity 의 변경낸 히스토리를 남기는 방법중에 하나인 envers 를 이용하여 남기는 방법을 알아보고자 합니다.

필수 설정

  • 의존성
compile("org.hibernate:hibernate-envers")

  • 루트 configuration class 에 @EnableJpaAuditing 설정
@Configuration
@ComponentScan
@EnableJpaAuditing
public class ServiceConfig { /* ... */ }

  • entity 에 설정
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Table(name = "table")
@Audited
@AuditTable("audit_table")
public class Table { }

추가 설정

  • 기본적인 설정대로 하면 REV 가 integer type 으로 생성이 됩니다. 하나의 DB에서 REVINFO table 은 같이 사용하게 되므로 되도록이면 bigint type 을 사용하도록 해야합니다.
@Entity
@RevisionEntity
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Table(name = "REVINFO")
public class LongRevisionEntity implements Serializable {
    // ...
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @RevisionNumber
    @EqualsAndHashCode.Include
    @Column(name = "REV")
    private Long id;

    @RevisionTimestamp
    @EqualsAndHashCode.Include
    @Column(name = "REVTSTMP")
    private Long timestamp;
    // ...
}

Tip

  • @OneToOne, @OneToMany, @ManyToOne 과 같은 field 의 join column 도 history 를 남기고 싶다면,
    public class Entity {
      // ...
      @Audited(targetAuditMode = NOT_AUDITED)
      @ToString.Exclude
      @ManyToOne(fetch = FetchType.LAZY)
      @JoinColumn(name = "join_column", foreignKey = @ForeignKey(value = ConstraintMode.NO_CONSTRAINT))
      private String joinColumn;
      // ...
    }
    
    • @Audited(targetAuditMode = NOT_AUDITED) 의 기본값은 RelationTargetAuditMode.AUDITED 입니다.
      • mapping 한 table 도 audit 을 설정을 했다면 상관 없지만, mapping 된 table 을 제외하고, join column 만 하고 싶다면 위와 같이 하면 됩니다.
  • @Version 을 설정한 column 도 history 를 남기고 싶다면,
    spring.datasource.jpa.properties.org.hibernate.envers.do_not_audit_optimistic_locking_field: false
    
    • spring boot 기준으로 위와 같이 설정값을 설정을 한다면 @Version 을 붙인 column 도 히스토리를 기록 할 수 있습니다.
  • audit table 생성 스크립트를 작성하기 귀찮다면,
    spring.jpa.properties.hibernate.hbm2ddl.auto: create-drop
    
    • 보통은 validate 로 되어 있을 건데요. local 에서 잠시 create-drop 으로 변경을 하고 나서 table 을 생성하는 script 를 복사하서 사용하면 됩니다.


hibernatehibernate envers Share Tweet +1