Reputation: 1265
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?
----------------- edit 1 -------------------
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;
}
...
}
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.
How should I edit my Session class?
Upvotes: 5
Views: 16280
Reputation: 21
Solution with "isDeleted" field will not work because @DbRef still retrieves the "isDeleted" records, I am playing around this problem too.
For your second question, you can use custom SpringHttpMessageConverters with GSON to hide "isDeleted" field.
Upvotes: 2
Reputation: 2868
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.
Upvotes: 11