Spring JPA Persistable Entity delete 안되는 현상

Entity의 Id값은 자동증가가 아닌 Id값으로 지정하기 위해 Persistable를 구현하였습니다.

Persistable 인터페이스는 Entity의 Id값이 시퀀스 등으로 자동증가되는 것이 아니라 직접 지정하는 경우 오류가 발생하는데, 이를 해결하기 위해 사용합니다.

@Getter
@NoArgsConstructor
@SuperBuilder
@Entity
public class Admin extends BaseEntity implements Serializable, Persistable<String> {
	@Id
    private String adminId;
    ...
        
    @Override
    public String getId() {
        return this.adminId;
    }

    @Override
    public boolean isNew() {
        return true;
    }
}

Service에서 다음과 같이 delete 메서드를 실행하면 아무일도 일어나지 않습니다.

@Transactional
public void deleteAdmin(String id) {
    this.adminRepository.findById(id).ifPresent(adminRepository::delete);
}

원인은 SimpleJpaRepository의 delete 메서드에서 isNew인 entity의 경우 return하는 로직 때문이었습니다.

image-20220615145017134

해결방법은 Entity의 isNew 오버라이드 메서드에서 생성일자를 체크하면 됩니다.

public class Admin extends BaseEntity implements Serializable, Persistable<String> {
    ...
    @Override
    public boolean isNew() {
        return this.createdDate == null;
    }
}

만약 날짜정보가 없는 Entity의 경우는 아래처럼 비영속성 변수를 생성하여 사용하면 됩니다.

public class Admin extends BaseEntity implements Serializable, Persistable<String> {
    @Transient
    private boolean isNew = true;
    
    public setNewEntity(boolean isNew) {
    	this.isNew = isNew;    
    }
    
    @Override
    public boolean isNew() {
        return this.isNew;
    }
}
@Transactional
public void deleteAdmin(String id) {
    this.adminRepository.findById(id).ifPresent(admin -> {
        admin.setNewEntity(false);
        adminRepository.delete(admin);
    });
}

댓글남기기