Search code examples
spring-integrationspring-integration-dsl

Spring integration Jpa | To insert row with MessagingGateway


I created MessagingGateway and 2 flows. I get the list correctly. When I create person, the program sleeps. Why? How can I fix this?

MyService myService = context.getBean(MyService.class);
System.out.println("persons = " + myService.getPersons());
System.out.println("person = " + myService.save(new Person(0, "Alex")));

@MessagingGateway
public interface MyService {
    @Gateway(requestChannel = "flow1.input")
    @Payload("new java.util.Date()")
    Collection<Person> getPersons();

    @Gateway(requestChannel = "flow2.input")
    Person save(Person person);
}

@Bean
public IntegrationFlow flow1(EntityManagerFactory entityManagerFactory) {
    return f -> f
            .handle(Jpa.retrievingGateway(entityManagerFactory)
                    .jpaQuery("from Person")
            );
}

 @Bean
 public IntegrationFlow flow2(EntityManagerFactory entityManagerFactory) {
        return f -> f
                .handle(Jpa.outboundAdapter(entityManagerFactory)
                                .entityClass(Person.class)
                                .persistMode(PersistMode.PERSIST),
                        e -> e.transactional(true));
 }

Solution

  • Because outbound channel adapter is a one-way call. There is no reply from such a component to return to your gateway invocation.

    See docs: https://docs.spring.io/spring-integration/docs/current/reference/html/endpoint-summary.html#endpoint-summary and theory:

    https://www.enterpriseintegrationpatterns.com/patterns/messaging/ChannelAdapter.html https://www.enterpriseintegrationpatterns.com/patterns/messaging/MessagingGateway.html

    You should consider to change your gateway method contract Person save(Person person); to this void save(Person person);. When gateway is void it mean that there is no reply expected and your program is going to exit from this block whenever the send is successful.