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>5.1.2.RELEASE</version> </dependency>
Gradle.
compile "org.springframework.integration:spring-integration-jpa:5.1.2.RELEASE"
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:
All JPA components perform their respective JPA operations by using one of the following:
The following sections describe each of these components in more detail.
The Spring Integration JPA support has been tested against the following persistence providers:
When using a persistence provider, you should ensure that the provider is compatible with JPA 2.1.
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:
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; }
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.
Certain configuration parameters are shared by all JPA components:
auto-startup
true
.
Optional.
id
EventDrivenConsumer
or PollingConsumer
.
Optional.
entity-manager-factory
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.
Note | |
---|---|
Usually, your Spring application context defines only a JPA entity manager factory, and the |
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
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
native-query
named-query
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.
The following example shows how to set an expression-based parameter:
<int-jpa:parameter expression="payload.name" name="firstName"/>
The following example shows how to set an value-based parameter:
<int-jpa:parameter name="name" type="java.lang.String" value="myName"/>
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"/>
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.
Note | |
---|---|
Unlike the |
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" entity-manager="em" auto-startup="true" query="select s from Student s" expect-single-result="true" max-results="" max-results-expression="" delete-after-poll="true" flush-after-delete="true"> <int:poller fixed-rate="2000" > <int:transactional propagation="REQUIRED" transaction-manager="transactionManager"/> </int:poller> </int-jpa:inbound-channel-adapter>
The channel over which the | |
The | |
Attribute signaling whether the component should automatically start when the application context starts.
The value defaults to | |
The JPA QL whose result are sent out as the payload of the message | |
This attribute tells whether the JPQL query gives a single entity in the result or a | |
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 | |
An expression that is evaluated to find the maximum number of results in a result set.
Mutually exclusive with | |
Set this value to | |
Set this value to |
The following listing shows all the values that can be set for an inbound-channel-adapter
:
<int-jpa:inbound-channel-adapter auto-startup="true" channel="" delete-after-poll="false" delete-per-row="false" entity-class="" entity-manager="" entity-manager-factory="" expect-single-result="false" id="" jpa-operations="" jpa-query="" named-query="" native-query="" parameter-source="" send-timeout=""> <int:poller ref="myPoller"/> </int-jpa:inbound-channel-adapter>
This lifecycle attribute signals whether this component should automatically start when the application context starts.
This attribute defaults to | |
The channel to which the adapter sends a message with the payload from performing the desired JPA operation. | |
A boolean flag that indicates whether to delete the selected records after they have been polled by the adapter.
By default, the value is | |
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 | |
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. | |
An instance of | |
An instance of | |
A boolean flag indicating whether the select operation is expected to return a single result or a | |
An implementation of | |
The JPA QL to be executed by this adapter. Optional. | |
The named query that needs to be executed by this adapter. Optional. | |
The native query executed by this adapter.
You can use any of the | |
An implementation of | |
Maximum amount of time (in milliseconds) to wait when sending a message to the channel. Optional. |
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()); } }
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 IntegrationFlows .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(); } }
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.
The following XML configures the outbound channel adapter to persist an entity to the database:
<int-jpa:outbound-channel-adapter channel="entityTypeChannel" entity-class="org.springframework.integration.jpa.test.entity.Student" persist-mode="PERSIST" entity-manager="em"/ >
The channel over which a valid JPA entity is sent to the JPA outbound channel adapter. | |
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. | |
The operation to be done by the adapter.
The valid values are | |
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.
Note | |
---|---|
As of Spring Integration 3.0, payloads to |
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" jpa-query="update Student s set s.firstName = :firstName where s.rollNumber = :rollNumber" entity-manager="em"> <int-jpa:parameter name="firstName" expression="payload['firstName']"/> <int-jpa:parameter name="rollNumber" expression="payload['rollNumber']"/> </int-jpa:outbound-channel-adapter>
The input channel over which the message is sent to the outbound channel adapter. | |
The JPA QL to execute.
This query may contain parameters that are evaluated by using the | |
The entity manager used by the adapter to perform the JPA operations. | |
The elements (one for each parameter) used to define the value of the parameter names for the JPA QL specified in the |
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.
Note | |
---|---|
Though specifying |
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.
Important | |
---|---|
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: " |
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)" 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>
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 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:
The following listing shows all the attributes that you can set on an outbound channel adapter:
<int-jpa:outbound-channel-adapter auto-startup="true" channel="" entity-class="" entity-manager="" entity-manager-factory="" id="" jpa-operations="" jpa-query="" named-query="" native-query="" order="" parameter-source-factory="" persist-mode="MERGE" flush="true" flush-size="10" clear-on-flush="true" use-payload-as-parameter-source="true" (16) <int:poller/> <int-jpa:transactional/> (17) <int-jpa:parameter/> (18) </int-jpa:outbound-channel-adapter>
Lifecycle attribute signaling whether this component should start during application context startup.
It defaults to | |
The channel from which the outbound adapter receives messages for performing the desired operation. | |
The fully qualified name of the entity class for the JPA Operation.
The | |
An instance of | |
An instance of | |
An implementation of | |
The JPA QL to be executed by this adapter. Optional. | |
The named query that needs to be executed by this adapter. Optional. | |
The native query to be executed by this adapter.
You can use any one of the | |
The order for this consumer when multiple consumers are registered, thereby managing load-balancing and failover.
It defaults to | |
An instance of | |
Accepts one of the following: | |
Set this value to | |
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 the | |
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 | |
If set to | |
Defines the transaction management attributes and the reference to the transaction manager to be used by the JPA adapter. Optional. | |
One or more |
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; } }
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()); } }
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 terminating 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:
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.
Note | |
---|---|
We recommend you first read the Section 22.6, “Outbound Channel Adapter” section and the Section 22.5, “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:
For configuration examples see Section 22.7.8, “JPA Outbound Gateway Samples”.
JPA Outbound Gateways always have access to the Spring Integration Message
as input.
Consequently, the following parameters is available:
parameter-source-factory
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
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.
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="" 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="" reply-timeout="" 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>
The channel from which the outbound gateway receives messages for performing the desired operation.
This attribute is similar to the | |
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 | |
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 |
The remaining attributes are described earlier in this chapter. See Section 22.5.1, “Configuration Parameter Reference” and Section 22.6.5, “Configuration Parameter Reference”.
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; } }
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")); } }
The following example shows all the attributes that you can set on a retrieving outbound gateway and describes the key attributes:
<int-jpa:retrieving-outbound-gateway request-channel="" auto-startup="true" delete-after-poll="false" delete-in-batch="false" entity-class="" id-expression="" entity-manager="" entity-manager-factory="" expect-single-result="false" id="" jpa-operations="" jpa-query="" max-results="" max-results-expression="" first-result="" first-result-expression="" 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>
(Since Spring Integration 4.0) The SpEL expression that determines the | |
A boolean flag indicating whether the select operation is expected to return a single result or a | |
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 | |
An expression that can be used to find the maximum number of results in a result set.
It is mutually exclusive with | |
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 | |
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 |
The remaining attributes are described earlier in this chapter. See Section 22.5.1, “Configuration Parameter Reference” and Section 22.6.5, “Configuration Parameter Reference”.
The following Spring Boot application shows an example of how configure the outbound 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 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; } }
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 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")); } }
Important | |
---|---|
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 JSR 317: Java™ Persistence 2.0 states in chapter 4.10, " " For more information, see JSR 317: Java™ Persistence 2.0 |
This section contains various examples of using the updating outbound gateway and the retrieving outbound gateway:
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" reply-channel="entityResponseChannel" entity-class="org.springframework.integration.jpa.test.entity.Student" entity-manager="em"/>
This is the request channel for the outbound gateway.
It is similar to the | |
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 |
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" entity-manager="em"> <int-jpa:parameter name="lastName" expression="payload"/> <int-jpa:parameter name="rollNumber" expression="headers['rollNumber']"/> </int-jpa:updating-outbound-gateway>
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.
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>
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"/>
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>
Note | |
---|---|
You can find a complete sample application that uses Spring Integration’s JPA adapter here. |