0

How to modify spring data jpa default query and delete method?

For example:

In the build environment, every table has a field enabled.

When delete this data, the field enabled is false

And when select the data, only select enabled is true.

So, spring data jpa default method can't do this.

How to modify this?

I find a way

    /**
     * 自己写的删除方法
     *
     * @param aLong 删除的id
     */
    @Modifying
    @Query("UPDATE Book SET enabled = false WHERE id = :id")
    @RestResource(exported = false)
    void delete(@Param("id") Long aLong);

    /**
     * 重写删除方法
     *
     * @param entity 删除的实体
     */
    @Override
    default void delete(Book entity){
        delete(entity.getId());
    }

But the JpaRepository has more methods and I have more tables.That is terrible!

Can you help me?

Thanks!

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348
EchoCow
  • 117
  • 1
  • 10

2 Answers2

1

You can't because Spring-data-rest is not intended to work like that. A HTTP DELETE will always delete the resource. What you want in fact is just updating an attribute value (set enabled from true to false). In fact, you don't have to implement anything to do what you are trying to do, because thanks to Spring-data-rest you can call PATCH (or UPDATE) on any resource to update it. When you delete the data just make a PATCH call instead of a DELETE call to set the enabled boolean to false.

PATCH http://base-url/resource/id
{
   "enabled" : false
}
Xavier FRANCOIS
  • 652
  • 4
  • 15
0

There is no JPA conformant way to do this. If you happen to use Hibernate you can you can customize the queries used for delete and selection.

See https://vladmihalcea.com/the-best-way-to-soft-delete-with-hibernate/ for details.

Jens Schauder
  • 77,657
  • 34
  • 181
  • 348