Soft Delete 구현

남예준·2025년 10월 11일

찾아보니 대체적으로

SQLDelete 어노테이션과 Where 어노테이션을 활용해서 구현을 하는 것 같다.

그런데 Where 어노테이션은 deprecated 되므로 SQLRestriction 어노테이션을 사용해서 구현하는 듯 보인다.

근데 우리 시스템은 deleted_by라는 삭제자 컬럼까지 확보해야 하는 상황이라 고민이 되는 부분이 있었다.

SQLDelete 어노테이션은 파라미터를 해당 엔터티 자체에서만 가지고 올 수 있어서 동적으로 변경되는 deleted_by 필드는 채우기 어려웠다.

그래서 BaseEntity에 markAsDelete, restore 두 개의 메소드를 만들어 직접 값을 넣어주도록 했다.

또한 지난 번 팀원의 코드에서 확인했던 SoftDelete Repository를 상속받는 것도 채택했다.

그리고 Where 절에 일일히 deleted된 애들을 배제하는 대신 SQLRestriction 어노테이션은 사용하기로 결정했다. 결과가 어떻게 나올지 궁금하긴 하다.

@Getter
@Entity
@SuperBuilder
@NoArgsConstructor
@Table(name = "h_item")
@SQLRestriction("deleted_at is NULL")
public class Item extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.UUID)
    @Column(name = "item_id")
    private UUID itemId;

    ...
    
    public void softDelete(Long deleterId) {
        super.markDeleted(deleterId);
    }

    public void restore() {
        super.restoreDeletion();
    }
}

이거 관련해서 SQLRestriction은 JPA Query 메소드를 통해서 조회를 하면 delete 된 친구를 배제하는데

admin 입장에서는 전부 조회될 필요가 있다. 그럴 때는! Native Query를 사용하면 포함해서 조회가 가능하다!

이렇게 softDelete Repository, SQLRestriction, Native Query를 사용해서 SoftDelete에 대한 기능 구현을 완료할 수 있었다.

0개의 댓글