'Spring Data Rest - Soft Delete

I've been using spring data rest without any problem but now I have a requirement that when a user performs a DELETE operation on a given entity i.e. DELETE /accounts/<id> I need to set a flag on the database marking that entity as deleted but i do want to keep the record.

Basically this means that I need to do an UPDATE instead of a DELETE operation in the database. I don't find any way to override the spring behavior for the delete(ID) method.

Some code:

@Entity
@Table(name = "account")
public class Account {

    /*
Default value for this field is false but when a receive a 
DELETE request for this entity i want to turn this flag 
to false instead of deleting the record.
    */
    @Column(name = "deleted")
    private boolean deleted;

...
}

Account Repository

@RepositoryRestResource
public interface AccountRepository extends JpaRepository<Account, Integer> {

}

Any ideas?



Solution 1:[1]

It's enough that you override delete method of your @RepositoryRestResource, like so:

@RepositoryRestResource
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {

    @Modifying
    @Query("update Product p set deleted = true where p = :p")
    void delete(Product p);

    @Query("select p FROM Product p WHERE p.deleted = false")
    Page<Product> findAll(Pageable pageable);
}

Solution 2:[2]

I think first you should use an interface to identify only the entities that will use the soft delete. Afterwards you can override the delete method. If the entity is instance of that interface set the deleted flag to true and call update else call the super implementation. Use SimpleJpaRepository instead of JpaRepository. Example for interfaces https://github.com/danjee/hibernate-mappings you can find here (Persistent and DefaultPersistent)

Solution 3:[3]

@Autowired
private AccountRepository accountRepository; 
@Override
   public void accountSoftDelete (Long id) {
        Optional<Account> account1= accountRepository.findById(id);
        account1.get().setDeleted(true);
        accountRepository.save(account1.get());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2
Solution 3 Murugan K