JPA Entity 변동(변경) 감지하기

By | 2022년 11월 6일
Table of Contents

JPA Entity 변동(변경) 감지하기

Entity 의 변동을 감지하여 추가작업을 수행할 수 있습니다.

DB 작업이 필요한 경우에 대해 Event 를 발생시키는 방법을 설명합니다.

함수추가

@Entity
public class IpgoMaster {

    @PostPersist
    void postPersist() {
        System.out.println("after insert");
    }

    @PostLoad
    void postLoad() {
        System.out.println("after select");
    }

    @PostUpdate
    void postUpdate() {
        System.out.println("after update");
    }
}

Listener 분리

public class IpgoMasterEntityListener {

    @PostLoad
    void postLoad(Object o) {
        if (o instanceof IpgoMaster) {
            System.out.println("11111 PostLoad" + ((IpgoMaster) o).getIpgoDate());
        }
    }

    @PostUpdate
    void postUpdate(Object o) {
        if (o instanceof IpgoMaster) {
            System.out.println("11111 PostUpdate" + ((IpgoMaster) o).getIpgoDate());
        }
    }
}
@Entity
@EntityListeners(value = {IpgoMasterEntityListener.class})
public class IpgoMaster extends BaseTimeEntity implements Persistable<Long> {

}

Event 발생

Listener 에서 바로 DB 를 호출하면 오류가 발생할 수 있다.
참조

public class IpgoMasterEntityEvent extends ApplicationEvent {

    private final IpgoMaster ipgoMaster;

    public IpgoMasterEntityEvent(IpgoMaster ipgoMaster) {
        super(ipgoMaster);
        this.ipgoMaster = ipgoMaster;
    }
}
@Component
@NoArgsConstructor
public class IpgoMasterEntityListener {

    private ApplicationEventPublisher publisher;

    @Autowired
    public IpgoMasterEntityListener(ApplicationEventPublisher publisher) {
        this.publisher = publisher;
    }

    @PostLoad
    void postLoad(IpgoMaster o) {
        if (o != null) {
            o.getHistory().setHistory(o);
        }
    }

    @PostUpdate
    void postUpdate(IpgoMaster o) {
        if (o != null) {
            publisher.publishEvent(new IpgoMasterEntityEvent(o));
        }
    }
}
@Component
@RequiredArgsConstructor
public class IpgoMasterEntityEventHandler {

    private final IpgoDetailService service;

    @EventListener
    public void handle(IpgoMasterEntityEvent event) {
        service.undelete(0L);
        System.out.println("ok");
    }
}

답글 남기기