Home > Back-end >  Retrieve the deleted record spring JPA
Retrieve the deleted record spring JPA

Time:06-14

I am working on a spring application. We have a specific requirement where when we get a specific event, we want to look it up in the DB. If we find the record in the DB, then we delete it from DB, create another event using the details and trigger it.

Now my concern is:

  • I do not want to use two different calls, one to find the record and another to delete the record.
  • I am looking for a way where we can delete the record using a custom query and simultaneously fetch the deleted record.
  • This saves two differnet calls to DB, one for fetch and another for delete.

What I found on the internet so far:

  • We can use the custom query for deletion using the annotation called @Modifying. But this does not allow us to return the object as a whole. You can only return void or int from the methods that are annotated using @Modifying.
  • We have removeBy or deleteBy named queries provided by spring. but this also returns int only and not the complete record object that is being deleted.

I am specifically looking for something like:

@Transactional
FulfilmentAcknowledgement deleteByEntityIdAndItemIdAndFulfilmentIdAndType(@Param(value = "entityId") String entityId, @Param(value = "itemId") String itemId,
                                                                              @Param(value = "fulfilmentId") Long fulfilmentId, @Param(value = "type") String type);

Is it possible to get the deleted record from DB and make the above call work?

CodePudding user response:

I could not find a way to retrieve the actual object being deleted either by custom @Query or by named queries. The only method that returns the object being deleted is deleteById or removeById, but for that, we need the primary key of the record that is being deleted. It is not always possible to have that primary key with us.

So far, the best way that I found to do this was:

  1. Fetch the record from DB using the custom query.
  2. Delete the record from DB by calling deleteById. Although, you can now delete it using any method since we would not be requiring the object being returned by deleteById. I still chose deleteById because my DB is indexed on the primary key and it is faster to delete it using that.
  3. We can use reactor or executor service to run the processes asynchronously and parallelly.
  • Related