membersound
membersound

Reputation: 86697

How to delete objects in ItemWriter?

I'm using spring-batch for data imports. But during the writer() step, I don't want to persist the items processed, but delete them (by id) from a database.

Question: the ItemWriters like JpaItemWriter are just for persisting items. Is there any writer that I could eg pass a CrudRepository and that calls repository.delete(id)?

Upvotes: 5

Views: 3049

Answers (1)

Michael Minella
Michael Minella

Reputation: 21463

The JpaItemWriter does not support deletions. However...we do have a RepositoryItemWriter that you can configure the method called. So in your case, you can use that in conjunction with a JpaRepository from Spring Data and configure the method to be called as a delete. This would delete the items you pass in (if you were to delete by id, you'd want to create a processor that took the item and returned the id). You can read more about the RepositoryItemWriter here: https://docs.spring.io/spring-batch/apidocs/org/springframework/batch/item/data/RepositoryItemWriter.html

As an alternative, you could subclass the JpaItemWriter and override the doWrite method to call entityManager.remove instead of the entityManager.merge that it currently does...

Upvotes: 5

Related Questions