【问题标题】:How to implement soft (logical) delete with MongoDB and Spring?如何使用 MongoDB 和 Spring 实现软(逻辑)删除?
【发布时间】:2015-11-26 08:58:20
【问题描述】:

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

@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);
  }
  ...    
}

将其更改为软删除的好方法是什么?

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

我现在明白我应该做什么的逻辑了,谢谢 Sarath Nair。但我不确定如何在 Spring 中实现这一点。我有一个 Session 对象:

@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 出现在数据库中,但我不希望通过网络服务发送该信息。 @Transient 不好,因为这样该字段就不会出现在数据库中,也不会出现在 HTTP 响应中。现在我在我的 HTTP 响应中发送 deleted: false

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

【问题讨论】:

  • 找到解决方案。由于 Spring 在内部使用 Jackson,@JsonIgnore 使得字段不会出现在响应中

标签: java spring mongodb


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    带有“isDeleted”字段的解决方案将不起作用,因为@DbRef 仍然检索“isDeleted”记录,我也在解决这个问题。

    对于第二个问题,您可以使用带有 GSON 的自定义 SpringHttpMessageConverters 来隐藏“isDeleted”字段。

    【讨论】:

    • 我在“isDeleted”字段中使用了@JsonIgnore,因为Spring 在内部使用了Jackson。现在该字段不会出现在 HTTP 响应中。
    • @potato300 我用的是 GSon,所以我不能用 @JsonIgnore 但我可以找到 @JsonIgnore 的替代品,谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-06-05
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 2016-07-08
    • 1970-01-01
    相关资源
    最近更新 更多