如何使用MongoDB和Spring实现软(逻辑)删除? [英] How to implement soft (logical) delete with MongoDB and Spring?

查看:422
本文介绍了如何使用MongoDB和Spring实现软(逻辑)删除?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有MongoDB的Spring Web应用程序.目前,我总是从数据库中永久删除数据.

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?

-----------------编辑1 -------------------

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

感谢Sarath Nair,我现在明白该怎么做.但是我不确定如何在Spring中实现这一点.我有一个Session对象:

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;
  }

  ...
}

我希望字段boolean isDeleted出现在数据库中,但我不想通过Web服务发送该信息. @Transient不好,因为该字段将不会显示在数据库或HTTP响应中.现在,我正在HTTP响应中发送deleted: false.

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.

我应该如何编辑我的Session类?

How should I edit my Session class?

推荐答案

集合中还有一个名为is_deleted的附加字段.对于新文档,将is_deleted插入为false.删除时,只需将该文档的此值更新为true.每当您需要从集合中读取文档时,请将is_deleted : false传递给集合.

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.

这篇关于如何使用MongoDB和Spring实现软(逻辑)删除?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆