[英]How to implement soft (logical) delete with MongoDB and Spring?
我有MongoDB的Spring網絡應用程序。 目前我總是從數據庫中永久刪除數據。
@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類?
在集合中有一個名為is_deleted
的附加字段。 對於新文檔,插入is_deleted
為false
。 刪除時只需將該值更新為該文檔的true
。 每當您需要從集合中讀取文檔時,請為集合傳遞is_deleted : false
。
使用“isDeleted”字段的解決方案將無效,因為@DbRef仍會檢索“isDeleted”記錄,我也在玩這個問題。
對於第二個問題,您可以使用自定義SpringHttpMessageConverters和GSON來隱藏“isDeleted”字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.