I have a table Stuff
defined as...
id, <fields>..., active
Active is the soft-delete flag and is always 1
or 0
. Long term this may go away in favor of a historical table.
public interface StuffRepository extends JpaRepository<StuffEntity, Long> {}
In code, we always use active records. Is there any way to get Spring to always append an active=1
condition to queries generated for this repository? Or more ideally allow me to extend the grammar used to generate the queries?
I understand that I can create named @queues
everywhere but then I lose the convenience of the generated queries. I also want to avoid polluting the interface with "active" methods.
I am using Hibernate 4.2 as my JPA implementation if that matters.
To implement a soft delete, you need to override Hibernate's default remove operation. You can do that with an @SQLDelete annotation. This annotation allows you to define a custom, native SQL query that Hibernate will execute when you delete the entity. You can see an example of it in the following code snippet.
And implementing soft delete is easy! You just add the “Is_Deleted” or “Delete_Date” column to your tables (or attributes to your Document) and replace all delete statement invocations in your application code to updates. And yes, you need to modify all retrieve statements to take into account this new attribute.
First of all you need to create a jpa query method that brings all records belong to id. After that you can do deleteAll() operation on List.
orphanRemoval is an entirely ORM-specific thing. It marks "child" entity to be removed when it's no longer referenced from the "parent" entity, e.g. when you remove the child entity from the corresponding collection of the parent entity.
@Where(clause="is_active=1")
is not the best way to handle soft delete with spring data jpa.
First, it only works with hibernate implement.
Second, you can never fetch soft deleted entities with spring data.
My solution is el provided by spring data. #{#entityName}
expression can be used on generic repository represent concrete entity type name.
And code will be like this:
//Override CrudRepository or PagingAndSortingRepository's query method: @Override @Query("select e from #{#entityName} e where e.deleteFlag=false") public List<T> findAll(); //Look up deleted entities @Query("select e from #{#entityName} e where e.deleteFlag=true") public List<T> recycleBin(); //Soft delete. @Query("update #{#entityName} e set e.deleteFlag=true where e.id=?1") @Modifying public void softDelete(String id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With