Search code examples
spring-integrationspring-jdbc

Spring Integration JdbcMessageHandler - payload with multiple items


How can I process multiple messages in the payload?

I tried the following:

@Bean
@ServiceActivator(inputChannel = "outChannel")
 public MessageHandler jdbcMessageHandler() {
    JdbcMessageHandler jdbcMessageHandler = new JdbcMessageHandler(getDataSource(), getSql());

     jdbcMessageHandler.setPreparedStatementSetter((ps, message) -> {
            Item[] items = ((Item[]) message.getPayload());
            Arrays.stream(items).forEach(item -> {                
                    ps.setString(1, item.getName());
            }
            ps.addBatch();
    } 
    return jdbcMessageHandler;
}
 

But only last message inserted multiple times. (Note: using java configuration and not xml for the beans)


Solution

  • See docs: https://docs.spring.io/spring-integration/reference/html/jdbc.html#batch-update

    the JdbcMessageHandler performs a JdbcOperations.batchUpdate() if the payload of the request message is an Iterable instance.

    Iterable, not an array as I see in your sample. So, consider to transform your array into a List and you should be good with handling a batch update for several items at once.