IT'S DO
728x90

# 라이프사이클 콜백

어노테이션실행 시점

@PrePersist 엔티티가 저장되기 직전 (INSERT SQL 전에 실행).
@PostPersist 엔티티가 저장된 직후 (INSERT SQL 실행 후 실행).
@PreUpdate 엔티티가 업데이트되기 직전 (UPDATE SQL 전에 실행).
@PostUpdate 엔티티가 업데이트된 직후 (UPDATE SQL 실행 후 실행).
@PreRemove 엔티티가 삭제되기 직전 (DELETE SQL 전에 실행).
@PostRemove 엔티티가 삭제된 직후 (DELETE SQL 실행 후 실행).
@PostLoad 엔티티가 DB에서 조회된 직후.

 

# 예제 :

@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String email;

    @Column(nullable = false)
    private String address;

    @Column(nullable = false)
    private String ssn; // 주민번호

    @PrePersist
    public void encryptSensitiveData() throws Exception {
        this.email = EncryptionUtil.encrypt(this.email);
        this.address = EncryptionUtil.encrypt(this.address);
        this.ssn = EncryptionUtil.encrypt(this.ssn);
    }

    @PostLoad
    public void decryptSensitiveData() throws Exception {
        this.email = EncryptionUtil.decrypt(this.email);
        this.address = EncryptionUtil.decrypt(this.address);
        this.ssn = EncryptionUtil.decrypt(this.ssn);
    }

    // Getter & Setter
}

 

=> User의 생성 api를 만들어서

@PrePersist로 이메일, 주소, 주민번호를 암호화 시켜서 DB에 넣고, 

조회 api를 호출할 때 @PostLoad로 인해 복호화 시킨 값을 가져올 때 사용함. 

 

# 결과 : 

DB : 

email : YXVzZGtsQGV4YW1wbGUuY29t 

address : U2VvdWwsIEtvcmVh 

ssn : MTIzNDU2LTEyMzQ1Njc=

 

Response : 

{ "email": "user@example.com", "address": "Seoul, Korea", "ssn": "123456-1234567" }

 

profile

IT'S DO

@멋진놈

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!