Search code examples
spring-integrationspring-integration-dsl

Spring Integration DSL: How do I delete a list of JPA entities?


I have a bunch of JPA Entities that I retrieve like this:

.handle(Jpa.retrievingGateway(myEntityManagerFactory).namedQuery(readQuery))
.transform(/* remove some of the entities from the message, leaving only the ones I want to delete */)

And now I would like to delete some of them. What is the best way to do this ? I'm thinking there must be some simple way to do it with a very simple or possibly even no explicit jpaQuery() at all ?

I'm imagining something like this:

.handle(Jpa.updatingGateway(myEntityManagerFactory)
    .jpaQuery("delete from MyTable m where m in :items")
    .parameter("items", ...(?)... )

or like this:

.handle(Jpa.deletingGateway(myEntityManagerFactory))

What's the right way to do this with the Spring Integration DSL ?


Solution

  • You can do it like this:

    .handle(Jpa.updatingGateway(entityManagerFactory).persistMode(PersistMode.DELETE))
    

    Although it works only for a single entity. So, consider to have your integration flow like this:

    .handle(Jpa.retrievingGateway(myEntityManagerFactory).namedQuery(readQuery))
    .transform(/* remove some of the entities from the message, leaving only the ones I want to delete */)
    .split()
    .handle(Jpa.updatingGateway(entityManagerFactory).persistMode(PersistMode.DELETE))
    

    I mean add a splitter before JPA gateway. Of course if your .transform() returns the list.

    I think we may make it more convenient for use-cases like yours if the payload of the message is an Iterable. There is already a JpaOperations.deleteInBatch(). So, the JpaExecutor.executeOutboundJpaOperationOnPersistentMode() could be improved in its branch:

    case DELETE:
                this.jpaOperations.delete(payload);
                if (this.flush) {
                    this.jpaOperations.flush();
                }
                return payload;
    

    Feel free to raise a GH issue and we will revise it eventually!