I was looking for a way to avoid deleting my users from DB, but instead to mark them as deleted and don’t bring them back in queries.
I found this plugin http://grails.org/plugin/hibernate-filter, which was a great tool for the task.
But when I tried to implement my solution, I passed trought same problems whose solutions wheren’t (or I was not able to find) on internet.
So, next, I describe the way that I solve the problem of soft delete.
In this example I will make my class User to handle it’s delete() method as a soft delete, setting the attribute lowDate with the actual date when delete() is called on an User instance. The idea is that users with lowDate != null will be ignored by GORM queries.
1) Intall Hibernate Filter Plugin. Look for the dependency at the plugin’s page: http://grails.org/plugin/hibernate-filter. Take a look at the documentation.
2) Add to Datasource the following:
3) Define your filter at the class:
Note: look at the way I defined the condition. The value it receives is sql, so be careful to name the attribute as it is on the database instead of the name on the class.
This will make GORM methods to avoid bringing users that have lowDate different than null.
4) Define beforeDelele in a way to avoid phisical deletion:
Note: I tried a simpler way to implement beforeDelete() that was
But when save() was called inside beforeDelete, the save method called beforeDelete, and so on, generating an StackOverflow. I don’t know why this happens.
5) Enable the filter on BootStrap:
That’s all, it show now work. To test the functionallity, here’s some sample spock tests:
Note: ‘build’ method is from build-test-data plugin.
Hope that that helps!