How to implement soft (logical) deletion using MongoDB and Spring?

I have a Spring web application with MongoDB. I am currently permanently deleting data from the 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 to a soft delete?

----------------- change 1 -------------------

Now I understand the logic of what I have to do, thanks to Sarat Naira. But I'm not sure 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 to boolean isDeletedbe present in the database, but I do not want to send this information using the web service. @Transientis not good, because then the field will not be displayed in the database or in the HTTP response. Right now I am sending deleted: falsein my HTTP response.

How do I change the Session class?

+4
2

is_deleted . is_deleted false . , true . , , is_deleted : false .

+2

"isDeleted" , @DbRef "isDeleted", .

SpringHttpMessageConverters GSON, isDeleted.

+1

Source: https://habr.com/ru/post/1617577/


All Articles