Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement soft (logical) delete with MongoDB and Spring?

I have Spring web app with MongoDB. Currently I always permanently delete data from database.

@Repository
public class SessionRepository extends CrudRepository implements SessionService {
  ...
  @Override
  public void insert(Session session) {
    saveRoom(session);
    getTemplate().insert(session);
  }

  @Override
  public void delete(Session session) {
    getTemplate().remove(session);
  }
  ...    
}

What would be a good way to change this into soft delete?

----------------- edit 1 -------------------

I understand the logic now what I should do, thanks Sarath Nair. But I am unsure how to implement this in Spring. I have a Session object:

@Document(collection = "session")
public class Session {

  @Id
  private String id;
  private Date startDate;
  private Date endDate;
//I just put this here
  private boolean deleted = false;

  public boolean isDeleted() {
    return deleted;
  }

  public void setDeleted(boolean deleted) {
    this.deleted = deleted;
  }

  ...
}

I want the field boolean isDeleted to be present in the database but I don't wan't to send that piece of information out with a web service. @Transient is no good because then the field won't show up in database nor in the HTTP response. Right now I am sending deleted: false in my HTTP response.

How should I edit my Session class?

like image 497
Kaarel Purde Avatar asked Dec 19 '22 22:12

Kaarel Purde


2 Answers

Have an additional field called is_deleted in collection. Insert is_deleted as false for new documents. When you are deleting just update this value to true for that document. Whenever you need to read documents from collection, pass is_deleted : false for the collection.

like image 121
Sarath Nair Avatar answered Mar 23 '23 01:03

Sarath Nair


Solution with "isDeleted" field will not work because @DbRef still retrieves the "isDeleted" records, I am playing around this problem too.

For your second question, you can use custom SpringHttpMessageConverters with GSON to hide "isDeleted" field.

like image 38
Vu Nguyen Avatar answered Mar 23 '23 01:03

Vu Nguyen