如何在MongoDB和Spring中实现软删除(逻辑删除)?

5

我有一个使用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,但是不想在web服务中发送这个数据。

@Transient不可用,因为这样字段既不会在数据库中显示,也不会在HTTP响应中显示。目前我正在通过HTTP响应发送deleted: false

我应该如何修改我的Session类?


找到解决方案了。由于Spring在内部使用Jackson,@JsonIgnore可以使字段不出现在响应中。 - Kaarel Purde
2个回答

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

如何在MongoDB文档中使用@Where(is_deleted=true)这样的功能呢?因为在查询过程中,立即排除所有“已删除”项目非常方便。 - undefined

2

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

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


1
我在“isDeleted”字段上使用了@JsonIgnore,因为Spring在内部使用Jackson。现在该字段不会出现在HTTP响应中。 - Kaarel Purde
@potato300 我使用GSon,所以我不能使用@JsonIgnore,但我可以找到@JsonIgnore的替代方法,谢谢! - Vu Nguyen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接