JPA Support

Spring Integration’s JPA (Java Persistence API) module provides components for performing various database operations using JPA.

You need to include this dependency into your project:

Maven
<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-jpa</artifactId>
    <version>6.0.3</version>
</dependency>
Gradle
compile "org.springframework.integration:spring-integration-jpa:6.0.3"

The JPA API must be included via some vendor-specific implementation, e.g. Hibernate ORM Framework.

The following components are provided:

These components can be used to perform select, create, update, and delete operations on the target databases by sending and receiving messages to them.

The JPA inbound channel adapter lets you poll and retrieve (select) data from the database by using JPA, whereas the JPA outbound channel adapter lets you create, update, and delete entities.

You can use outbound gateways for JPA to persist entities to the database, letting you continue the flow and execute further components downstream. Similarly, you can use an outbound gateway to retrieve entities from the database.

For example, you may use the outbound gateway, which receives a Message with a userId as payload on its request channel, to query the database, retrieve the user entity, and pass it downstream for further processing.

Recognizing these semantic differences, Spring Integration provides two separate JPA outbound gateways:

  • Retrieving outbound gateway

  • Updating outbound gateway

Functionality

All JPA components perform their respective JPA operations by using one of the following:

  • Entity classes

  • Java Persistence Query Language (JPQL) for update, select and delete (JPQL does not support inserts)

  • Native Query

  • Named Query

The following sections describe each of these components in more detail.

Supported Persistence Providers

The Spring Integration JPA support has been tested against Hibernate persistence provider.

Java Implementation

Each of the provided components uses the o.s.i.jpa.core.JpaExecutor class, which, in turn, uses an implementation of the o.s.i.jpa.core.JpaOperations interface. JpaOperations operates like a typical Data Access Object (DAO) and provides methods such as find, persist, executeUpdate, and so on. For most use cases, the default implementation (o.s.i.jpa.core.DefaultJpaOperations) should be sufficient. However, you can specify your own implementation if you require custom behavior.

To initialize a JpaExecutor, you must use one of the constructors that accept one of:

  • EntityManagerFactory

  • EntityManager

  • JpaOperations

The following example shows how to initialize a JpaExecutor with an entityManagerFactory and use it in an outbound gateway:

@Bean
public JpaExecutor jpaExecutor() {
    JpaExecutor executor = new JpaExecutor(this.entityManagerFactory);
    executor.setJpaParameters(Collections.singletonList(new JpaParameter("firstName", null, "#this")));
    executor.setUsePayloadAsParameterSource(true);
    executor.setExpectSingleResult(true);
    return executor;
}

@ServiceActivator(inputChannel = "getEntityChannel")
@Bean
public MessageHandler retrievingJpaGateway() {
    JpaOutboundGateway gateway = new JpaOutboundGateway(jpaExecutor());
    gateway.setGatewayType(OutboundGatewayType.RETRIEVING);
    gateway.setOutputChannelName("resultsChannel");
    return gateway;
}

Namespace Support

When using XML namespace support, the underlying parser classes instantiate the relevant Java classes for you. Thus, you typically need not deal with the inner workings of the JPA adapter. This section documents the XML namespace support provided by Spring Integration and shows you how to use the XML Namespace support to configure the JPA components.

Common XML Namespace Configuration Attributes

Certain configuration parameters are shared by all JPA components:

auto-startup

Lifecycle attribute that signals whether this component should be started during application context startup. Defaults to true. Optional.

id

Identifies the underlying Spring bean definition, which is an instance of either EventDrivenConsumer or PollingConsumer. Optional.

entity-manager-factory

The reference to the JPA entity manager factory that the adapter uses to create the EntityManager. You must provide this attribute, the entity-manager attribute, or the jpa-operations attribute.

entity-manager

The reference to the JPA Entity Manager that the component uses. You must provide this attribute, the entity-manager-factory attribute, or the jpa-operations attribute.

Usually, your Spring application context defines only a JPA entity manager factory, and the EntityManager is injected by using the @PersistenceContext annotation. This approach does not apply for the Spring Integration JPA components. Usually, injecting the JPA entity manager factory is best, but, when you want to inject an EntityManager explicitly, you have to define a SharedEntityManagerBean. For more information, see the relevant Javadoc.

The following example shows how to explicitly include an entity manager factory:

<bean id="entityManager"
      class="org.springframework.orm.jpa.support.SharedEntityManagerBean">
    <property name="entityManagerFactory" ref="entityManagerFactoryBean" />
</bean>
jpa-operations

A reference to a bean that implements the JpaOperations interface. In rare cases, it might be advisable to provide your own implementation of the JpaOperations interface instead of relying on the default implementation (org.springframework.integration.jpa.core.DefaultJpaOperations). If you use the jpa-operations attribute, you must not provide the JPA entity manager or JPA entity manager factory, because JpaOperations wraps the necessary datasource.

entity-class

The fully qualified name of the entity class. The exact semantics of this attribute vary, depending on whether we are performing a persist or update operation or whether we are retrieving objects from the database.

When retrieving data, you can specify the entity-class attribute to indicate that you would like to retrieve objects of this type from the database. In that case, you must not define any of the query attributes (jpa-query, native-query, or named-query).

When persisting data, the entity-class attribute indicates the type of object to persist. If not specified (for persist operations) the entity class is automatically retrieved from the message’s payload.

jpa-query

Defines the JPA query (Java Persistence Query Language) to be used.

native-query

Defines the native SQL query to be used.

named-query

Refers to a named query. A named query can be defined in either Native SQL or JPAQL, but the underlying JPA persistence provider handles that distinction internally.

Providing JPA Query Parameters

To provide parameters, you can use the parameter XML element. It has a mechanism that lets you provide parameters for queries that are based on either the Java Persistence Query Language (JPQL) or native SQL queries. You can also provide parameters for named queries.

Expression-based Parameters

The following example shows how to set an expression-based parameter:

<int-jpa:parameter expression="payload.name" name="firstName"/>
Value-based Parameters

The following example shows how to set an value-based parameter:

<int-jpa:parameter name="name" type="java.lang.String" value="myName"/>
Positional Parameters

The following example shows how to set an expression-based parameter:

<int-jpa:parameter expression="payload.name"/>
<int-jpa:parameter type="java.lang.Integer" value="21"/>

Transaction Handling

All JPA operations (such as INSERT, UPDATE, and DELETE) require a transaction to be active whenever they are performed. For inbound channel adapters, you need do nothing special. It works similarly to the way we configure transaction managers with pollers that are used with other inbound channel adapters. The following XML example configures a transaction manager that uses a poller with an inbound channel adapter:

<int-jpa:inbound-channel-adapter
    channel="inboundChannelAdapterOne"
    entity-manager="em"
    auto-startup="true"
    jpa-query="select s from Student s"
    expect-single-result="true"
    delete-after-poll="true">
    <int:poller fixed-rate="2000" >
        <int:transactional propagation="REQUIRED"
            transaction-manager="transactionManager"/>
    </int:poller>
</int-jpa:inbound-channel-adapter>

However, you may need to specifically start a transaction when using an outbound channel adapter or gateway. If a DirectChannel is an input channel for the outbound adapter or gateway and if the transaction is active in the current thread of execution, the JPA operation is performed in the same transaction context. You can also configure this JPA operation to run as a new transaction, as the following example shows:

<int-jpa:outbound-gateway
    request-channel="namedQueryRequestChannel"
    reply-channel="namedQueryResponseChannel"
    named-query="updateStudentByRollNumber"
    entity-manager="em"
    gateway-type="UPDATING">
    <int-jpa:parameter name="lastName" expression="payload"/>
    <int-jpa:parameter name="rollNumber" expression="headers['rollNumber']"/>
		<int-jpa:transactional propagation="REQUIRES_NEW"
        transaction-manager="transactionManager"/>
</int-jpa:outbound-gateway>

In the preceding example, the transactional element of the outbound gateway or adapter specifies the transaction attributes. It is optional to define this child element if you have DirectChannel as an input channel to the adapter and you want the adapter to execute the operations in the same transaction context as the caller. If, however, you use an ExecutorChannel, you must have the transactional element, because the invoking client’s transaction context is not propagated.

Unlike the transactional element of the poller, which is defined in Spring Integration’s namespace, the transactional element for the outbound gateway or adapter is defined in the JPA namespace.

Inbound Channel Adapter

An inbound channel adapter is used to execute a select query over the database using JPA QL and return the result. The message payload is either a single entity or a List of entities. The following XML configures an inbound-channel-adapter:

<int-jpa:inbound-channel-adapter channel="inboundChannelAdapterOne"  (1)
                    entity-manager="em"                              (2)
                    auto-startup="true"                              (3)
                    query="select s from Student s"                  (4)
                    expect-single-result="true"                      (5)
                    max-results=""                                   (6)
                    max-results-expression=""                        (7)
                    delete-after-poll="true"                         (8)
                    flush-after-delete="true">                       (9)
    <int:poller fixed-rate="2000" >
      <int:transactional propagation="REQUIRED" transaction-manager="transactionManager"/>
    </int:poller>
</int-jpa:inbound-channel-adapter>
1 The channel over which the inbound-channel-adapter puts the messages (with the payload) after executing the JPA QL in the query attribute.
2 The EntityManager instance used to perform the required JPA operations.
3 Attribute signaling whether the component should automatically start when the application context starts. The value defaults to true.
4 The JPA QL whose result are sent out as the payload of the message
5 This attribute tells whether the JPQL query gives a single entity in the result or a List of entities. If the value is set to true, the single entity is sent as the payload of the message. If, however, multiple results are returned after setting this to true, a MessagingException is thrown. The value defaults to false.
6 This non-zero, non-negative integer value tells the adapter not to select more than the given number of rows on execution of the select operation. By default, if this attribute is not set, all possible records are selected by the query. This attribute is mutually exclusive with max-results-expression. Optional.
7 An expression that is evaluated to find the maximum number of results in a result set. Mutually exclusive with max-results. Optional.
8 Set this value to true if you want to delete the rows received after execution of the query. You must ensure that the component operates as part of a transaction. Otherwise, you may encounter an exception such as: java.lang.IllegalArgumentException: Removing a detached instance …​
9 Set this value to true if you want to flush the persistence context immediately after deleting received entities and if you do not want to rely on the flushMode of the EntityManager. The value defaults to false.

Configuration Parameter Reference

The following listing shows all the values that can be set for an inbound-channel-adapter:

<int-jpa:inbound-channel-adapter
  auto-startup="true"           (1)
  channel=""                    (2)
  delete-after-poll="false"     (3)
  delete-per-row="false"        (4)
  entity-class=""               (5)
  entity-manager=""             (6)
  entity-manager-factory=""     (7)
  expect-single-result="false"  (8)
  id=""
  jpa-operations=""             (9)
  jpa-query=""                  (10)
  named-query=""                (11)
  native-query=""               (12)
  parameter-source=""           (13)
  send-timeout="">              (14)
  <int:poller ref="myPoller"/>
 </int-jpa:inbound-channel-adapter>
1 This lifecycle attribute signals whether this component should automatically start when the application context starts. This attribute defaults to true. Optional.
2 The channel to which the adapter sends a message with the payload from performing the desired JPA operation.
3 A boolean flag that indicates whether to delete the selected records after they have been polled by the adapter. By default, the value is false (that is, the records are not deleted). You must ensure that the component operates as part of a transaction. Otherwise, you may encounter an exception, such as: java.lang.IllegalArgumentException: Removing a detached instance …​. Optional.
4 A boolean flag that indicates whether the records can be deleted in bulk or must be deleted one record at a time. By default, the value is false (that is, the records can be bulk-deleted). Optional.
5 The fully qualified name of the entity class to be queried from the database. The adapter automatically builds a JPA Query based on the entity class name. Optional.
6 An instance of jakarta.persistence.EntityManager used to perform the JPA operations. Optional.
7 An instance of jakarta.persistence.EntityManagerFactory used to obtain an instance of jakarta.persistence.EntityManager that performs the JPA operations. Optional.
8 A boolean flag indicating whether the select operation is expected to return a single result or a List of results. If this flag is set to true, the single entity selected is sent as the payload of the message. If multiple entities are returned, an exception is thrown. If false, the List of entities is sent as the payload of the message. The value defaults to false. Optional.
9 An implementation of org.springframework.integration.jpa.core.JpaOperations used to perform the JPA operations. We recommend not providing an implementation of your own but using the default org.springframework.integration.jpa.core.DefaultJpaOperations implementation. You can use any of the entity-manager, entity-manager-factory, or jpa-operations attributes. Optional.
10 The JPA QL to be executed by this adapter. Optional.
11 The named query that needs to be executed by this adapter. Optional.
12 The native query executed by this adapter. You can use any of the jpa-query, named-query, entity-class, or native-query attributes. Optional.
13 An implementation of o.s.i.jpa.support.parametersource.ParameterSource used to resolve the values of the parameters in the query. Ignored if the entity-class attribute has a value. Optional.
14 Maximum amount of time (in milliseconds) to wait when sending a message to the channel. Optional.

Configuring with Java Configuration

The following Spring Boot application shows an example of how to configure the inbound adapter with Java:

@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public JpaExecutor jpaExecutor() {
        JpaExecutor executor = new JpaExecutor(this.entityManagerFactory);
        jpaExecutor.setJpaQuery("from Student");
        return executor;
    }

    @Bean
    @InboundChannelAdapter(channel = "jpaInputChannel",
                     poller = @Poller(fixedDelay = "${poller.interval}"))
    public MessageSource<?> jpaInbound() {
        return new JpaPollingChannelAdapter(jpaExecutor());
    }

    @Bean
    @ServiceActivator(inputChannel = "jpaInputChannel")
    public MessageHandler handler() {
        return message -> System.out.println(message.getPayload());
    }

}

Configuring with the Java DSL

The following Spring Boot application shows an example of how to configure the inbound adapter with the Java DSL:

@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public IntegrationFlow pollingAdapterFlow() {
        return IntegrationFlow
            .from(Jpa.inboundAdapter(this.entityManagerFactory)
                        .entityClass(StudentDomain.class)
                        .maxResults(1)
                        .expectSingleResult(true),
                e -> e.poller(p -> p.trigger(new OnlyOnceTrigger())))
            .channel(c -> c.queue("pollingResults"))
            .get();
    }

}

Outbound Channel Adapter

The JPA outbound channel adapter lets you accept messages over a request channel. The payload can either be used as the entity to be persisted or used with the headers in the parameter expressions for a JPQL query. The following sections cover the possible ways of performing these operations.

Using an Entity Class

The following XML configures the outbound channel adapter to persist an entity to the database:

<int-jpa:outbound-channel-adapter channel="entityTypeChannel"               (1)
    entity-class="org.springframework.integration.jpa.test.entity.Student"  (2)
    persist-mode="PERSIST"                                                  (3)
    entity-manager="em"/ >                                                  (4)
1 The channel over which a valid JPA entity is sent to the JPA outbound channel adapter.
2 The fully qualified name of the entity class accepted by the adapter to be persisted in the database. You can actually leave off this attribute in most cases as the adapter can determine the entity class automatically from the Spring Integration message payload.
3 The operation to be done by the adapter. The valid values are PERSIST, MERGE, and DELETE. The default value is MERGE.
4 The JPA entity manager to be used.

These four attributes of the outbound-channel-adapter configure it to accept entities over the input channel and process them to PERSIST, MERGE, or DELETE the entities from the underlying data source.

As of Spring Integration 3.0, payloads to PERSIST or MERGE can also be of type java.lang.Iterable. In that case, each object returned by the Iterable is treated as an entity and persisted or merged using the underlying EntityManager. Null values returned by the iterator are ignored.
Starting with version 5.5.4, the JpaOutboundGateway, with a JpaExecutor configured with PersistMode.DELETE, can accept an Iterable payload to perform a batch removal persistent operation for the provided entities.

Using JPA Query Language (JPA QL)

The previous section showed how to perform a PERSIST action by using an entity. This section shows how to use an outbound channel adapter with JPA QL.

The following XML configures the outbound channel adapter to persist an entity to the database:

<int-jpa:outbound-channel-adapter channel="jpaQlChannel"                                      (1)
  jpa-query="update Student s set s.firstName = :firstName where s.rollNumber = :rollNumber"  (2)
  entity-manager="em">                                                                        (3)
    <int-jpa:parameter name="firstName"  expression="payload['firstName']"/>                  (4)
    <int-jpa:parameter name="rollNumber" expression="payload['rollNumber']"/>
</int-jpa:outbound-channel-adapter>
1 The input channel over which the message is sent to the outbound channel adapter.
2 The JPA QL to execute. This query may contain parameters that are evaluated by using the parameter element.
3 The entity manager used by the adapter to perform the JPA operations.
4 The elements (one for each parameter) used to define the value of the parameter names for the JPA QL specified in the query attribute.

The parameter element accepts an attribute whose name corresponds to the named parameter specified in the provided JPA QL (point 2 in the preceding example). The value of the parameter can either be static or be derived by using an expression. The static value and the expression to derive the value are specified using the value and expression attributes, respectively. These attributes are mutually exclusive.

If the value attribute is specified, you can provide an optional type attribute. The value of this attribute is the fully qualified name of the class whose value is represented by the value attribute. By default, the type is assumed to be a java.lang.String. The following example shows how to define a JPA parameter:

<int-jpa:outbound-channel-adapter ...
>
    <int-jpa:parameter name="level" value="2" type="java.lang.Integer"/>
    <int-jpa:parameter name="name" expression="payload['name']"/>
</int-jpa:outbound-channel-adapter>

As the preceding example shows, you can use multiple parameter elements within an outbound channel adapter element and define some parameters by using expressions and others with static values. However, take care not to specify the same parameter name multiple times. You should provide one parameter element for each named parameter specified in the JPA query. For example, we specify two parameters: level and name. The level attribute is a static value of type java.lang.Integer, while the name attribute is derived from the payload of the message.

Though specifying select is valid for JPA QL, it makes no sense to do so. Outbound channel adapters do not return any result. If you want to select some values, consider using the outbound gateway instead.

Using Native Queries

This section describes how to use native queries to perform operations with the JPA outbound channel adapter. Using native queries is similar to using JPA QL, except that the queries are native database queries. By using native queries, we lose database vendor independence, which we get using JPA QL.

One of the things we can achieve by using native queries is to perform database inserts, which is not possible with JPA QL. (To perform inserts, we send JPA entities to the channel adapter, as described earlier). Below is a small xml fragment that demonstrates the use of native query to insert values in a table.

Named parameters may not be supported by your JPA provider in conjunction with native SQL queries. While they work fine with Hibernate, OpenJPA and EclipseLink do not support them. See https://issues.apache.org/jira/browse/OPENJPA-111. Section 3.8.12 of the JPA 2.0 spec states: “Only positional parameter binding and positional access to result items may be portably used for native queries.”

The following example configures an outbound-channel-adapter with a native query:

<int-jpa:outbound-channel-adapter channel="nativeQlChannel"
  native-query="insert into STUDENT_TABLE(FIRST_NAME,LAST_UPDATED) values (:lastName,:lastUpdated)"  (1)
  entity-manager="em">
    <int-jpa:parameter name="lastName" expression="payload['updatedLastName']"/>
    <int-jpa:parameter name="lastUpdated" expression="new java.util.Date()"/>
</int-jpa:outbound-channel-adapter>
1 The native query executed by this outbound channel adapter.

Note that the other attributes (such as channel and entity-manager) and the parameter element have the same semantics as they do for JPA QL.

Using Named Queries

Using named queries is similar to using JPA QL or a native query, except that we specify a named query instead of a query. First, we cover how to define a JPA named query. Then we cover how to declare an outbound channel adapter to work with a named query. If we have an entity called Student, we can use annotations on the Student class to define two named queries: selectStudent and updateStudent. The following example shows how to do so:

@Entity
@Table(name="Student")
@NamedQueries({
    @NamedQuery(name="selectStudent",
        query="select s from Student s where s.lastName = 'Last One'"),
    @NamedQuery(name="updateStudent",
        query="update Student s set s.lastName = :lastName,
               lastUpdated = :lastUpdated where s.id in (select max(a.id) from Student a)")
})
public class Student {

...
}

Alternatively, you can use orm.xml to define named queries as the following example shows:

<entity-mappings ...>
    ...
    <named-query name="selectStudent">
        <query>select s from Student s where s.lastName = 'Last One'</query>
    </named-query>
</entity-mappings>

Now that we have shown how to define named queries by using annotations or by using orm.xml, we now show a small XML fragment that defines an outbound-channel-adapter by using a named query, as the following example shows:

<int-jpa:outbound-channel-adapter channel="namedQueryChannel"
            named-query="updateStudent"	 (1)
            entity-manager="em">
        <int-jpa:parameter name="lastName" expression="payload['updatedLastName']"/>
        <int-jpa:parameter name="lastUpdated" expression="new java.util.Date()"/>
</int-jpa:outbound-channel-adapter>
1 The named query that we want the adapter to execute when it receives a message over the channel.

Configuration Parameter Reference

The following listing shows all the attributes that you can set on an outbound channel adapter:

<int-jpa:outbound-channel-adapter
  auto-startup="true"  (1)
  channel=""  (2)
  entity-class=""  (3)
  entity-manager=""  (4)
  entity-manager-factory=""  (5)
  id=""
  jpa-operations=""  (6)
  jpa-query=""  (7)
  named-query=""  (8)
  native-query=""  (9)
  order=""  (10)
  parameter-source-factory=""   (11)
  persist-mode="MERGE"   (12)
  flush="true"   (13)
  flush-size="10"   (14)
  clear-on-flush="true"   (15)
  use-payload-as-parameter-source="true"   (16)
	<int:poller/>
	<int-jpa:transactional/>    (17)
	<int-jpa:parameter/>    (18)
</int-jpa:outbound-channel-adapter>
1 Lifecycle attribute signaling whether this component should start during application context startup. It defaults to true. Optional.
2 The channel from which the outbound adapter receives messages for performing the desired operation.
3 The fully qualified name of the entity class for the JPA Operation. The entity-class, query, and named-query attributes are mutually exclusive. Optional.
4 An instance of jakarta.persistence.EntityManager used to perform the JPA operations. Optional.
5 An instance of jakarta.persistence.EntityManagerFactory used to obtain an instance of jakarta.persistence.EntityManager, which performs the JPA operations. Optional.
6 An implementation of org.springframework.integration.jpa.core.JpaOperations used to perform the JPA operations. We recommend not providing an implementation of your own but using the default org.springframework.integration.jpa.core.DefaultJpaOperations implementation. You can use any one of the entity-manager, entity-manager-factory, or jpa-operations attributes. Optional.
7 The JPA QL to be executed by this adapter. Optional.
8 The named query that needs to be executed by this adapter. Optional.
9 The native query to be executed by this adapter. You can use any one of the jpa-query, named-query, or native-query attributes. Optional.
10 The order for this consumer when multiple consumers are registered, thereby managing load-balancing and failover. It defaults to Ordered.LOWEST_PRECEDENCE. Optional.
11 An instance of o.s.i.jpa.support.parametersource.ParameterSourceFactory used to get an instance of o.s.i.jpa.support.parametersource.ParameterSource, which is used to resolve the values of the parameters in the query. Ignored if you perform operations by using a JPA entity. The parameter sub-elements are mutually exclusive with the parameter-source-factory attribute and must be configured on the provided ParameterSourceFactory. Optional.
12 Accepts one of the following: PERSIST, MERGE, or DELETE. Indicates the operation that the adapter needs to perform. Relevant only if you use an entity for JPA operations. Ignored if you provide JPA QL, a named query, or a native query. It defaults to MERGE. Optional. As of Spring Integration 3.0, payloads to persist or merge can also be of type java.lang.Iterable. In that case, each object returned by the Iterable is treated as an entity and persisted or merged by using the underlying EntityManager. Null values returned by the iterator are ignored.
13 Set this value to true if you want to flush the persistence context immediately after persist, merge, or delete operations and do not want to rely on the flushMode of the EntityManager. It defaults to false. Applies only if you did not specify the flush-size attribute. If this attribute is set to true, flush-size is implicitly set to 1, if no other value configured it.
14 Set this attribute to a value greater than '0' if you want to flush the persistence context immediately after persist, merge or delete operations and do not want to rely on the flushMode of the EntityManager. The default value is set to 0, which means "'no flush'". This attribute is geared towards messages with Iterable payloads. For instance, if flush-size is set to 3, then entityManager.flush() is called after every third entity. Furthermore, entityManager.flush() is called once more after the entire loop. If the 'flush-size' attribute is specified with a value greater than '0', you need not configure the flush attribute.
15 Set this value to 'true' if you want to clear the persistence context immediately after each flush operation. The attribute’s value is applied only if the flush attribute is set to true or if the flush-size attribute is set to a value greater than 0.
16 If set to true, the payload of the message is used as a source for parameters. If set to false, however, the entire Message is available as a source for parameters. Optional.
17 Defines the transaction management attributes and the reference to the transaction manager to be used by the JPA adapter. Optional.
18 One or more parameter attributes — one for each parameter used in the query. The value or expression is evaluated to compute the value of the parameter. Optional.

Configuring with Java Configuration

The following Spring Boot application shows an example of how to configure the outbound adapter with Java:

@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
@IntegrationComponentScan
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @MessagingGateway
    interface JpaGateway {

       @Gateway(requestChannel = "jpaPersistChannel")
       @Transactional
       void persistStudent(StudentDomain payload);

    }

    @Bean
    public JpaExecutor jpaExecutor() {
        JpaExecutor executor = new JpaExecutor(this.entityManagerFactory);
        jpaExecutor.setEntityClass(StudentDomain.class);
        jpaExecutor.setPersistMode(PersistMode.PERSIST);
        return executor;
    }

    @Bean
    @ServiceActivator(channel = "jpaPersistChannel")
    public MessageHandler jpaOutbound() {
        JpaOutboundGateway adapter = new JpaOutboundGateway(jpaExecutor());
        adapter.setProducesReply(false);
        return adapter;
    }

}

Configuring with the Java DSL

The following Spring Boot application shows an example of how to configure the outbound adapter with the Java DSL:

@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public IntegrationFlow outboundAdapterFlow() {
        return f -> f
                .handle(Jpa.outboundAdapter(this.entityManagerFactory)
                                .entityClass(StudentDomain.class)
                                .persistMode(PersistMode.PERSIST),
                        e -> e.transactional());
    }

}

Outbound Gateways

The JPA inbound channel adapter lets you poll a database to retrieve one or more JPA entities. The retrieved data is consequently used to start a Spring Integration flow that uses the retrieved data as message payload.

Additionally, you can use JPA outbound channel adapters at the end of your flow in order to persist data, essentially stopping the flow at the end of the persistence operation.

However, how can you execute JPA persistence operations in the middle of a flow? For example, you may have business data that you are processing in your Spring Integration message flow and that you would like to persist, yet you still need to use other components further downstream. Alternatively, instead of polling the database using a poller, you need to execute JPQL queries and actively retrieve data, which is then processed in subsequent components within your flow.

This is where JPA Outbound Gateways come into play. They give you the ability to persist data as well as retrieving data. To facilitate these uses, Spring Integration provides two types of JPA outbound gateways:

  • Updating outbound gateway

  • Retrieving outbound gateway

Whenever the outbound gateway is used to perform an action that saves, updates, or solely deletes some records in the database, you need to use an updating outbound gateway. If, for example, you use an entity to persist it, a merged and persisted entity is returned as a result. In other cases, the number of records affected (updated or deleted) is returned instead.

When retrieving (selecting) data from the database, we use a retrieving outbound gateway. With a retrieving outbound gateway, we can use JPQL, Named Queries (native or JPQL-based), or Native Queries (SQL) for selecting the data and retrieving the results.

An updating outbound gateway is functionally similar to an outbound channel adapter, except that an updating outbound gateway sends a result to the gateway’s reply channel after performing the JPA operation.

A retrieving outbound gateway is similar to an inbound channel adapter.

We recommend you first read the Outbound Channel Adapter section and the Inbound Channel Adapter sections earlier in this chapter, as most of the common concepts are explained there.

This similarity was the main factor to use the central JpaExecutor class to unify common functionality as much as possible.

Common for all JPA outbound gateways and similar to the outbound-channel-adapter, we can use for performing various JPA operations:

  • Entity classes

  • JPA Query Language (JPQL)

  • Native query

  • Named query

For configuration examples see JPA Outbound Gateway Samples.

Common Configuration Parameters

JPA Outbound Gateways always have access to the Spring Integration Message as input. Consequently, the following parameters is available:

parameter-source-factory

An instance of o.s.i.jpa.support.parametersource.ParameterSourceFactory used to get an instance of o.s.i.jpa.support.parametersource.ParameterSource. The ParameterSource is used to resolve the values of the parameters provided in the query. If you perform operations by using a JPA entity, the parameter-source-factory attribute is ignored. The parameter sub-elements are mutually exclusive with the parameter-source-factory and they have to be configured on the provided ParameterSourceFactory. Optional.

use-payload-as-parameter-source

If set to true, the payload of the Message is used as a source for parameters. If set to false, the entire Message is available as a source for parameters. If no JPA Parameters are passed in, this property defaults to true. This means that, if you use a default BeanPropertyParameterSourceFactory, the bean properties of the payload are used as a source for parameter values for the JPA query. However, if JPA Parameters are passed in, this property, by default, evaluates to false. The reason is that JPA Parameters let you provide SpEL Expressions. Therefore, it is highly beneficial to have access to the entire Message, including the headers. Optional.

Updating Outbound Gateway

The following listing shows all the attributes that you can set on an updating-outbound-gateway and describes the key attributes:

<int-jpa:updating-outbound-gateway request-channel=""  (1)
    auto-startup="true"
    entity-class=""
    entity-manager=""
    entity-manager-factory=""
    id=""
    jpa-operations=""
    jpa-query=""
    named-query=""
    native-query=""
    order=""
    parameter-source-factory=""
    persist-mode="MERGE"
    reply-channel=""  (2)
    reply-timeout=""  (3)
    use-payload-as-parameter-source="true">

    <int:poller/>
    <int-jpa:transactional/>

    <int-jpa:parameter name="" type="" value=""/>
    <int-jpa:parameter name="" expression=""/>
</int-jpa:updating-outbound-gateway>
1 The channel from which the outbound gateway receives messages for performing the desired operation. This attribute is similar to the channel attribute of the outbound-channel-adapter. Optional.
2 The channel to which the gateway send the response after performing the required JPA operation. If this attribute is not defined, the request message must have a replyChannel header. Optional.
3 Specifies the time the gateway waits to send the result to the reply channel. Only applies when the reply channel itself might block the send operation (for example, a bounded QueueChannel that is currently full). By default, the gateway waits indefinitely. The value is specified in milliseconds. Optional.

The remaining attributes are described earlier in this chapter. See Configuration Parameter Reference and Configuration Parameter Reference.

Configuring with Java Configuration

The following Spring Boot application shows an example of how configure the outbound adapter with Java:

@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
@IntegrationComponentScan
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @MessagingGateway
    interface JpaGateway {

       @Gateway(requestChannel = "jpaUpdateChannel")
       @Transactional
       void updateStudent(StudentDomain payload);

    }

    @Bean
    @ServiceActivator(channel = "jpaUpdateChannel")
    public MessageHandler jpaOutbound() {
        JpaOutboundGateway adapter =
               new JpaOutboundGateway(new JpaExecutor(this.entityManagerFactory));
        adapter.setOutputChannelName("updateResults");
        return adapter;
    }

}

Configuring with the Java DSL

The following Spring Boot application shows an example of how to configure the outbound adapter using the Java DSL:

@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public IntegrationFlow updatingGatewayFlow() {
        return f -> f
                .handle(Jpa.updatingGateway(this.entityManagerFactory),
                        e -> e.transactional(true))
                .channel(c -> c.queue("updateResults"));
    }

}

Retrieving Outbound Gateway

The following example demonstrates how to configure a retrieving outbound gateway:

Java DSL
@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public IntegrationFlow retrievingGatewayFlow() {
        return f -> f
                .handle(Jpa.retrievingGateway(this.entityManagerFactory)
                       .jpaQuery("from Student s where s.id = :id")
                       .expectSingleResult(true)
                       .parameterExpression("id", "payload"))
                .channel(c -> c.queue("retrieveResults"));
    }

}
Kotlin DSL
@Bean
fun retrievingGatewayFlow() =
    integrationFlow {
        handle(Jpa.retrievingGateway(this.entityManagerFactory)
                .jpaQuery("from Student s where s.id = :id")
                .expectSingleResult(true)
                .parameterExpression("id", "payload"))
        channel { queue("retrieveResults") }
    }
Java
@SpringBootApplication
@EntityScan(basePackageClasses = StudentDomain.class)
public class JpaJavaApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder(JpaJavaApplication.class)
            .web(false)
            .run(args);
    }

    @Autowired
    private EntityManagerFactory entityManagerFactory;


    @Bean
    public JpaExecutor jpaExecutor() {
        JpaExecutor executor = new JpaExecutor(this.entityManagerFactory);
        jpaExecutor.setJpaQuery("from Student s where s.id = :id");
        executor.setJpaParameters(Collections.singletonList(new JpaParameter("id", null, "payload")));
        jpaExecutor.setExpectSingleResult(true);
        return executor;
    }

    @Bean
    @ServiceActivator(channel = "jpaRetrievingChannel")
    public MessageHandler jpaOutbound() {
        JpaOutboundGateway adapter = new JpaOutboundGateway(jpaExecutor());
        adapter.setOutputChannelName("retrieveResults");
        adapter.setGatewayType(OutboundGatewayType.RETRIEVING);
        return adapter;
    }

}
XML
<int-jpa:retrieving-outbound-gateway request-channel=""
    auto-startup="true"
    delete-after-poll="false"
    delete-in-batch="false"
    entity-class=""
    id-expression=""              (1)
    entity-manager=""
    entity-manager-factory=""
    expect-single-result="false"  (2)
    id=""
    jpa-operations=""
    jpa-query=""
    max-results=""                (3)
    max-results-expression=""     (4)
    first-result=""               (5)
    first-result-expression=""    (6)
    named-query=""
    native-query=""
    order=""
    parameter-source-factory=""
    reply-channel=""
    reply-timeout=""
    use-payload-as-parameter-source="true">
    <int:poller></int:poller>
    <int-jpa:transactional/>

    <int-jpa:parameter name="" type="" value=""/>
    <int-jpa:parameter name="" expression=""/>
</int-jpa:retrieving-outbound-gateway>
1 (Since Spring Integration 4.0) The SpEL expression that determines the primaryKey value for EntityManager.find(Class entityClass, Object primaryKey) method against the requestMessage as the root object of evaluation context. The entityClass argument is determined from the entity-class attribute, if present. Otherwise, it is determined from the payload class. All other attributes are disallowed if you use id-expression. Optional.
2 A boolean flag indicating whether the select operation is expected to return a single result or a List of results. If this flag is set to true, a single entity is sent as the payload of the message. If multiple entities are returned, an exception is thrown. If false, the List of entities is sent as the payload of the message. It defaults to false. Optional.
3 This non-zero, non-negative integer value tells the adapter not to select more than the specified number of rows on execution of the select operation. By default, if this attribute is not set, all the possible records are selected by given query. This attribute is mutually exclusive with max-results-expression. Optional.
4 An expression that can be used to find the maximum number of results in a result set. It is mutually exclusive with max-results. Optional.
5 This non-zero, non-negative integer value tells the adapter the first record from which results are to be retrieved. This attribute is mutually exclusive with first-result-expression. Version 3.0 introduced this attribute. Optional.
6 This expression is evaluated against the message, to find the position of the first record in the result set. This attribute is mutually exclusive to first-result. Version 3.0 introduced this attribute. Optional.

When you choose to delete entities upon retrieval, and you have retrieved a collection of entities, by default, entities are deleted on a per-entity basis. This may cause performance issues.

Alternatively, you can set attribute deleteInBatch to true, which performs a batch delete. However, the limitation of doing so is that cascading deletes are not supported.

JSR 317: Java™ Persistence 2.0 states in chapter 4.10, “Bulk Update and Delete Operations” that:

“A delete operation only applies to entities of the specified class and its subclasses. It does not cascade to related entities.”

For more information, see JSR 317: Java™ Persistence 2.0

Starting with version 6.0, the Jpa.retrievingGateway() returns an empty list result when there are no entities returned by the query. Previously null was returned ending the flow, or throwing an exception, depending on requiresReply. Or, to revert to the previous behavior, add a filter after the gateway to filter out empty lists. It requires extra configuration in applications where empty list handling is a part of the downstream logic. See Splitter Discard Channel for possible empty list handling options.

JPA Outbound Gateway Samples

This section contains various examples of using the updating outbound gateway and the retrieving outbound gateway:

Update by Using an Entity Class

In the following example, an updating outbound gateway is persisted by using the org.springframework.integration.jpa.test.entity.Student entity class as a JPA defining parameter:

<int-jpa:updating-outbound-gateway request-channel="entityRequestChannel"  (1)
    reply-channel="entityResponseChannel"  (2)
    entity-class="org.springframework.integration.jpa.test.entity.Student"
    entity-manager="em"/>
1 This is the request channel for the outbound gateway. It is similar to the channel attribute of the outbound-channel-adapter.
2 This is where a gateway differs from an outbound adapter. This is the channel over which the reply from the JPA operation is received. If, however, you are not interested in the reply received and want only to perform the operation, using a JPA outbound-channel-adapter is the appropriate choice. In this example, where we use an entity class, the reply is the entity object that was created or merged as a result of the JPA operation.
Update using JPQL

The following example updates an entity by using the Java Persistence Query Language (JPQL), which mandates using an updating outbound gateway:

<int-jpa:updating-outbound-gateway request-channel="jpaqlRequestChannel"
  reply-channel="jpaqlResponseChannel"
  jpa-query="update Student s set s.lastName = :lastName where s.rollNumber = :rollNumber"  (1)
  entity-manager="em">
    <int-jpa:parameter name="lastName" expression="payload"/>
    <int-jpa:parameter name="rollNumber" expression="headers['rollNumber']"/>
</int-jpa:updating-outbound-gateway>
1 The JPQL query that the gateway executes. Since we used updating outbound gateway, only update and delete JPQL queries would be sensible choices.

When you send a message with a String payload that also contains a header called rollNumber with a long value, the last name of the student with the specified roll number is updated to the value in the message payload. When using an updating gateway, the return value is always an integer value, which denotes the number of records affected by execution of the JPA QL.

Retrieving an Entity using JPQL

The following example uses a retrieving outbound gateway and JPQL to retrieve (select) one or more entities from the database:

<int-jpa:retrieving-outbound-gateway request-channel="retrievingGatewayReqChannel"
    reply-channel="retrievingGatewayReplyChannel"
    jpa-query="select s from Student s where s.firstName = :firstName and s.lastName = :lastName"
    entity-manager="em">
    <int-jpa:parameter name="firstName" expression="payload"/>
    <int-jpa:parameter name="lastName" expression="headers['lastName']"/>
</int-jpa:outbound-gateway>
Retrieving an Entity by Using id-expression

The following example uses a retrieving outbound gateway with id-expression to retrieve (find) one and only one entity from the database: The primaryKey is the result of id-expression evaluation. The entityClass is a class of Message payload.

<int-jpa:retrieving-outbound-gateway
	request-channel="retrievingGatewayReqChannel"
    reply-channel="retrievingGatewayReplyChannel"
    id-expression="payload.id"
    entity-manager="em"/>
Update using a Named Query

Using a named query is basically the same as using a JPQL query directly. The difference is that the named-query attribute is used instead, as the following example shows:

<int-jpa:updating-outbound-gateway request-channel="namedQueryRequestChannel"
    reply-channel="namedQueryResponseChannel"
    named-query="updateStudentByRollNumber"
    entity-manager="em">
    <int-jpa:parameter name="lastName" expression="payload"/>
    <int-jpa:parameter name="rollNumber" expression="headers['rollNumber']"/>
</int-jpa:outbound-gateway>
You can find a complete sample application that uses Spring Integration’s JPA adapter here.