Data Access
Data Access
Data Access
Version 5.2.4.RELEASE
Back to index
1. Transaction Management
1.1. Advantages of the Spring Framework’s Transaction Support Model
1.1.1. Global Transactions
1.1.2. Local Transactions
1.1.3. Spring Framework’s Consistent Programming Model
1.2. Understanding the Spring Framework Transaction Abstraction
1.3. Synchronizing Resources with Transactions
1.3.1. High-level Synchronization Approach
1.3.2. Low-level Synchronization Approach
1.3.3. TransactionAwareDataSourceProxy
1.4. Declarative transaction management
1.4.1. Understanding the Spring Framework’s Declarative Transaction Implementation
1.4.2. Example of Declarative Transaction Implementation
1.4.3. Rolling Back a Declarative Transaction
1.4.4. Configuring Different Transactional Semantics for Different Beans
1.4.5. <tx:advice/> Settings
1.4.6. Using @Transactional
@Transactional Settings
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 1/163
3/10/2020 Data Access
Understanding PROPAGATION_REQUIRES_NEW
Understanding PROPAGATION_NESTED
1.4.8. Advising Transactional Operations
1.4.9. Using @Transactional with AspectJ
1.5. Programmatic Transaction Management
1.5.1. Using the TransactionTemplate
Specifying Transaction Settings
1.5.2. Using the PlatformTransactionManager
1.6. Choosing Between Programmatic and Declarative Transaction Management
1.7. Transaction-bound Events
1.8. Application server-specific integration
1.8.1. IBM WebSphere
1.8.2. Oracle WebLogic Server
1.9. Solutions to Common Problems
1.9.1. Using the Wrong Transaction Manager for a Specific DataSource
1.10. Further Resources
2. DAO Support
2.1. Consistent Exception Hierarchy
2.2. Annotations Used to Configure DAO or Repository Classes
3. Data Access with JDBC
3.1. Choosing an Approach for JDBC Database Access
3.2. Package Hierarchy
3.3. Using the JDBC Core Classes to Control Basic JDBC Processing and Error Handling
3.3.1. Using JdbcTemplate
Querying ( SELECT )
Updating ( INSERT , UPDATE , and DELETE ) with JdbcTemplate
Other JdbcTemplate Operations
JdbcTemplate Best Practices
Using LocalEntityManagerFactoryBean
Obtaining an EntityManagerFactory from JNDI
Using LocalContainerEntityManagerFactoryBean
Dealing with Multiple Persistence Units
Background Bootstrapping
4.4.2. Implementing DAOs Based on JPA: EntityManagerFactory and EntityManager
4.4.3. Spring-driven JPA transactions
4.4.4. Understanding JpaDialect and JpaVendorAdapter
4.4.5. Setting up JPA with JTA Transaction Management
4.4.6. Native Hibernate Setup and Native Hibernate Transactions for JPA Interaction
5. Marshalling XML by Using Object-XML Mappers
5.1. Introduction
5.1.1. Ease of configuration
5.1.2. Consistent Interfaces
5.1.3. Consistent Exception Hierarchy
5.2. Marshaller and Unmarshaller
5.2.1. Understanding Marshaller
5.2.2. Understanding Unmarshaller
5.2.3. Understanding XmlMappingException
5.3. Using Marshaller and Unmarshaller
5.4. XML Configuration Namespace
5.5. JAXB
5.5.1. Using Jaxb2Marshaller
XML Configuration Namespace
5.6. JiBX
5.6.1. Using JibxMarshaller
XML Configuration Namespace
5.7. XStream
5.7.1. Using XStreamMarshaller
6. Appendix
6.1. XML Schemas
6.1.1. The tx Schema
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 5/163
3/10/2020 Data Access
This part of the reference documentation is concerned with data access and the interaction
between the data access layer and the business or service layer.
1. Transaction Management
Comprehensive transaction support is among the most compelling reasons to use the Spring
Framework. The Spring Framework provides a consistent abstraction for transaction
management that delivers the following benefits:
A consistent programming model across different transaction APIs, such as Java Transaction
API (JTA), JDBC, Hibernate, and the Java Persistence API (JPA).
A simpler API for programmatic transaction management than complex transaction APIs,
such as JTA.
The following sections describe the Spring Framework’s transaction features and technologies:
Advantages of the Spring Framework’s transaction support model describes why you would
use the Spring Framework’s transaction abstraction instead of EJB Container-Managed
Transactions (CMT) or choosing to drive local transactions through a proprietary API, such as
Hibernate.
Understanding the Spring Framework transaction abstraction outlines the core classes and
describes how to configure and obtain DataSource instances from a variety of sources.
Synchronizing resources with transactions describes how the application code ensures that
resources are created, reused, and cleaned up properly.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 6/163
3/10/2020 Data Access
Programmatic transaction management covers support for programmatic (that is, explicitly
coded) transaction management.
Transaction bound event describes how you could use application events within a
transaction.
The chapter also includes discussions of best practices, application server integration, and
solutions to common problems.
Previously, the preferred way to use global transactions was through EJB CMT (Container
Managed Transaction). CMT is a form of declarative transaction management (as distinguished
from programmatic transaction management). EJB CMT removes the need for transaction-
related JNDI lookups, although the use of EJB itself necessitates the use of JNDI. It removes most
but not all of the need to write Java code to control transactions. The significant downside is that
CMT is tied to JTA and an application server environment. Also, it is only available if one chooses
to implement business logic in EJBs (or at least behind a transactional EJB facade). The
negatives of EJB in general are so great that this is not an attractive proposition, especially in
the face of compelling alternatives for declarative transaction management.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 7/163
3/10/2020 Data Access
With programmatic transaction management, developers work with the Spring Framework
transaction abstraction, which can run over any underlying transaction infrastructure. With the
preferred declarative model, developers typically write little or no code related to transaction
management and, hence, do not depend on the Spring Framework transaction API or any other
transaction API.
In particular, you do not need an application server purely for declarative transactions
through EJBs. In fact, even if your application server has powerful JTA capabilities, you
may decide that the Spring Framework’s declarative transactions offer more power and a
more productive programming model than EJB CMT.
Typically, you need an application server’s JTA capability only if your application needs to
handle transactions across multiple resources, which is not a requirement for many
applications. Many high-end applications use a single, highly scalable database (such as
Oracle RAC) instead. Stand-alone transaction managers (such as Atomikos Transactions
and JOTM) are other options. Of course, you may need other application server
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 8/163
3/10/2020 Data Access
capabilities, such as Java Message Service (JMS) and Java EE Connector Architecture
(JCA).
The Spring Framework gives you the choice of when to scale your application to a fully
loaded application server. Gone are the days when the only alternative to using EJB CMT
or JTA was to write code with local transactions (such as those on JDBC connections) and
face a hefty rework if you need that code to run within global, container-managed
transactions. With the Spring Framework, only some of the bean definitions in your
configuration file need to change (rather than your code).
Java Kotlin
JAVA
public interface PlatformTransactionManager {
This is primarily a service provider interface (SPI), although you can use it programmatically
from your application code. Because PlatformTransactionManager is an interface, it can be easily
mocked or stubbed as necessary. It is not tied to a lookup strategy, such as JNDI.
PlatformTransactionManager implementations are defined like any other object (or bean) in the
Spring Framework IoC container. This benefit alone makes Spring Framework transactions a
worthwhile abstraction, even when you work with JTA. You can test transactional code much
more easily than if it used JTA directly.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 9/163
3/10/2020 Data Access
Again, in keeping with Spring’s philosophy, the TransactionException that can be thrown by any
of the PlatformTransactionManager interface’s methods is unchecked (that is, it extends the
java.lang.RuntimeException class). Transaction infrastructure failures are almost invariably
fatal. In rare cases where application code can actually recover from a transaction failure, the
application developer can still choose to catch and handle TransactionException . The salient
point is that developers are not forced to do so.
Propagation: Typically, all code executed within a transaction scope runs in that transaction.
However, you can specify the behavior if a transactional method is executed when a
transaction context already exists. For example, code can continue running in the existing
transaction (the common case), or the existing transaction can be suspended and a new
transaction created. Spring offers all of the transaction propagation options familiar from
EJB CMT. To read about the semantics of transaction propagation in Spring, see Transaction
Propagation.
Isolation: The degree to which this transaction is isolated from the work of other
transactions. For example, can this transaction see uncommitted writes from other
transactions?
Timeout: How long this transaction runs before timing out and being automatically rolled
back by the underlying transaction infrastructure.
Read-only status: You can use a read-only transaction when your code reads but does not
modify data. Read-only transactions can be a useful optimization in some cases, such as
when you use Hibernate.
These settings reflect standard transactional concepts. If necessary, refer to resources that
discuss transaction isolation levels and other core transaction concepts. Understanding these
concepts is essential to using the Spring Framework or any transaction management solution.
The TransactionStatus interface provides a simple way for transactional code to control
transaction execution and query transaction status. The concepts should be familiar, as they are
common to all transaction APIs. The following listing shows the TransactionStatus interface:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 10/163
3/10/2020 Data Access
Java Kotlin
JAVA
public interface TransactionStatus extends SavepointManager {
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
void flush();
boolean isCompleted();
}
You can define a JDBC DataSource by creating a bean similar to the following:
XML
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
The related PlatformTransactionManager bean definition then has a reference to the DataSource
definition. It should resemble the following example:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 11/163
3/10/2020 Data Access
XML
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
If you use JTA in a Java EE container, then you use a container DataSource , obtained through JNDI,
in conjunction with Spring’s JtaTransactionManager . The following example shows what the JTA
and JNDI lookup version would look like:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/jee
https://www.springframework.org/schema/jee/spring-jee.xsd">
</beans>
The JtaTransactionManager does not need to know about the DataSource (or any other specific
resources) because it uses the container’s global transaction management infrastructure.
The preceding definition of the dataSource bean uses the <jndi-lookup/> tag from the jee
namespace. For more information see The JEE Schema.
You can also use easily Hibernate local transactions, as shown in the following examples. In this
case, you need to define a Hibernate LocalSessionFactoryBean , which your application code can
use to obtain Hibernate Session instances.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 12/163
3/10/2020 Data Access
The DataSource bean definition is similar to the local JDBC example shown previously and, thus,
is not shown in the following example.
If the DataSource (used by any non-JTA transaction manager) is looked up through JNDI and
managed by a Java EE container, it should be non-transactional, because the Spring
Framework (rather than the Java EE container) manages the transactions.
The txManager bean in this case is of the HibernateTransactionManager type. In the same way as
the DataSourceTransactionManager needs a reference to the DataSource , the
HibernateTransactionManager needs a reference to the SessionFactory . The following example
declares sessionFactory and txManager beans:
XML
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="mappingResources">
<list>
<value>org/springframework/samples/petclinic/hibernate/petclinic.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<value>
hibernate.dialect=${hibernate.dialect}
</value>
</property>
</bean>
If you use Hibernate and Java EE container-managed JTA transactions, you should use the same
JtaTransactionManager as in the previous JTA example for JDBC, as the following example shows:
XML
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager"/>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 13/163
3/10/2020 Data Access
If you use JTA, your transaction manager definition should look the same, regardless of
what data access technology you use, be it JDBC, Hibernate JPA, or any other supported
technology. This is due to the fact that JTA transactions are global transactions, which can
enlist any transactional resource.
In all these cases, application code does not need to change. You can change how transactions
are managed merely by changing configuration, even if that change means moving from local to
global transactions or vice versa.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 14/163
3/10/2020 Data Access
transactions are (optionally) synchronized, and exceptions that occur in the process are properly
mapped to a consistent API.
For example, in the case of JDBC, instead of the traditional JDBC approach of calling the
getConnection() method on the DataSource , you can instead use Spring’s
org.springframework.jdbc.datasource.DataSourceUtils class, as follows:
JAVA
Connection conn = DataSourceUtils.getConnection(dataSource);
If an existing transaction already has a connection synchronized (linked) to it, that instance is
returned. Otherwise, the method call triggers the creation of a new connection, which is
(optionally) synchronized to any existing transaction and made available for subsequent reuse
in that same transaction. As mentioned earlier, any SQLException is wrapped in a Spring
Framework CannotGetJdbcConnectionException , one of the Spring Framework’s hierarchy of
unchecked DataAccessException types. This approach gives you more information than can be
obtained easily from the SQLException and ensures portability across databases and even
across different persistence technologies.
This approach also works without Spring transaction management (transaction synchronization
is optional), so you can use it whether or not you use Spring for transaction management.
Of course, once you have used Spring’s JDBC support, JPA support, or Hibernate support, you
generally prefer not to use DataSourceUtils or the other helper classes, because you are much
happier working through the Spring abstraction than directly with the relevant APIs. For example,
if you use the Spring JdbcTemplate or jdbc.object package to simplify your use of JDBC, correct
connection retrieval occurs behind the scenes and you need not write any special code.
1.3.3. TransactionAwareDataSourceProxy
At the very lowest level exists the TransactionAwareDataSourceProxy class. This is a proxy for a
target DataSource , which wraps the target DataSource to add awareness of Spring-managed
transactions. In this respect, it is similar to a transactional JNDI DataSource , as provided by a
Java EE server.
You should almost never need or want to use this class, except when existing code must be
called and passed a standard JDBC DataSource interface implementation. In that case, it is
possible that this code is usable but is participating in Spring-managed transactions. You can
write your new code by using the higher-level abstractions mentioned earlier.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 15/163
3/10/2020 Data Access
Most Spring Framework users choose declarative transaction management. This option
has the least impact on application code and, hence, is most consistent with the ideals of a
non-invasive lightweight container.
The Spring Framework’s declarative transaction management is made possible with Spring
aspect-oriented programming (AOP). However, as the transactional aspects code comes with the
Spring Framework distribution and may be used in a boilerplate fashion, AOP concepts do not
generally have to be understood to make effective use of this code.
The Spring Framework’s declarative transaction management is similar to EJB CMT, in that you
can specify transaction behavior (or lack of it) down to the individual method level. You can
make a setRollbackOnly() call within a transaction context, if necessary. The differences
between the two types of transaction management are:
Unlike EJB CMT, which is tied to JTA, the Spring Framework’s declarative transaction
management works in any environment. It can work with JTA transactions or local
transactions by using JDBC, JPA, or Hibernate by adjusting the configuration files.
You can apply the Spring Framework declarative transaction management to any class, not
merely special classes such as EJBs.
The Spring Framework offers declarative rollback rules, a feature with no EJB equivalent. Both
programmatic and declarative support for rollback rules is provided.
The Spring Framework lets you customize transactional behavior by using AOP. For example,
you can insert custom behavior in the case of transaction rollback. You can also add arbitrary
advice, along with transactional advice. With EJB CMT, you cannot influence the container’s
transaction management, except with setRollbackOnly() .
The Spring Framework does not support propagation of transaction contexts across remote
calls, as high-end application servers do. If you need this feature, we recommend that you use
EJB. However, consider carefully before using such a feature, because, normally, one does not
want transactions to span remote calls.
The concept of rollback rules is important. They let you specify which exceptions (and
throwables) should cause automatic rollback. You can specify this declaratively, in
configuration, not in Java code. So, although you can still call setRollbackOnly() on the
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 16/163
3/10/2020 Data Access
TransactionStatus object to roll back the current transaction back, most often you can specify a
rule that MyApplicationException must always result in rollback. The significant advantage to
this option is that business objects do not depend on the transaction infrastructure. For
example, they typically do not need to import Spring transaction APIs or other Spring APIs.
Although EJB container default behavior automatically rolls back the transaction on a system
exception (usually a runtime exception), EJB CMT does not roll back the transaction
automatically on an application exception (that is, a checked exception other than
java.rmi.RemoteException ). While the Spring default behavior for declarative transaction
management follows EJB convention (roll back is automatic only on unchecked exceptions), it is
often useful to customize this behavior.
The most important concepts to grasp with regard to the Spring Framework’s declarative
transaction support are that this support is enabled via AOP proxies and that the transactional
advice is driven by metadata (currently XML- or annotation-based). The combination of AOP with
transactional metadata yields an AOP proxy that uses a TransactionInterceptor in conjunction
with an appropriate PlatformTransactionManager implementation to drive transactions around
method invocations.
The following images shows a Conceptual view of calling a method on a transactional proxy:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 17/163
3/10/2020 Data Access
Java Kotlin
JAVA
// the service interface that we want to make transactional
package x.y.service;
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 18/163
3/10/2020 Data Access
Java Kotlin
JAVA
package x.y.service;
@Override
public Foo getFoo(String fooName) {
// ...
}
@Override
public Foo getFoo(String fooName, String barName) {
// ...
}
@Override
public void insertFoo(Foo foo) {
// ...
}
@Override
public void updateFoo(Foo foo) {
// ...
}
}
Assume that the first two methods of the FooService interface, getFoo(String) and
getFoo(String, String) , must execute in the context of a transaction with read-only semantics,
and that the other methods, insertFoo(Foo) and updateFoo(Foo) , must execute in the context of
a transaction with read-write semantics. The following configuration is explained in detail in the
next few paragraphs:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 19/163
3/10/2020 Data Access
XML
<!-- from the file 'context.xml' -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- this is the service object that we want to make transactional -->
<bean id="fooService" class="x.y.service.DefaultFooService"/>
<!-- the transactional advice (what 'happens'; see the <aop:advisor/> bean below) -->
<tx:advice id="txAdvice" transaction-manager="txManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- ensure that the above transactional advice runs for any execution
of an operation defined by the FooService interface -->
<aop:config>
<aop:pointcut id="fooServiceOperation" expression="execution(* x.y.service.FooService.*(
<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceOperation"/>
</aop:config>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 20/163
3/10/2020 Data Access
</beans>
Examine the preceding configuration. It assumes that you want to make a service object, the
fooService bean, transactional. The transaction semantics to apply are encapsulated in the
<tx:advice/> definition. The <tx:advice/> definition reads as “all methods, on starting with get ,
are to execute in the context of a read-only transaction, and all other methods are to execute
with the default transaction semantics”. The transaction-manager attribute of the <tx:advice/>
tag is set to the name of the PlatformTransactionManager bean that is going to drive the
transactions (in this case, the txManager bean).
You can omit the transaction-manager attribute in the transactional advice ( <tx:advice/> )
if the bean name of the PlatformTransactionManager that you want to wire in has the name
transactionManager . If the PlatformTransactionManager bean that you want to wire in has
any other name, you must use the transaction-manager attribute explicitly, as in the
preceding example.
The <aop:config/> definition ensures that the transactional advice defined by the txAdvice bean
executes at the appropriate points in the program. First, you define a pointcut that matches the
execution of any operation defined in the FooService interface ( fooServiceOperation ). Then you
associate the pointcut with the txAdvice by using an advisor. The result indicates that, at the
execution of a fooServiceOperation , the advice defined by txAdvice is run.
The expression defined within the <aop:pointcut/> element is an AspectJ pointcut expression.
See the AOP section for more details on pointcut expressions in Spring.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 21/163
3/10/2020 Data Access
A common requirement is to make an entire service layer transactional. The best way to do this
is to change the pointcut expression to match any operation in your service layer. The following
example shows how to do so:
XML
<aop:config>
<aop:pointcut id="fooServiceMethods" expression="execution(* x.y.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="fooServiceMethods"/>
</aop:config>
In the preceding example, it is assumed that all your service interfaces are defined in the
x.y.service package. See the AOP section for more details.
Now that we have analyzed the configuration, you may be asking yourself, “What does all this
configuration actually do?”
The configuration shown earlier is used to create a transactional proxy around the object that is
created from the fooService bean definition. The proxy is configured with the transactional
advice so that, when an appropriate method is invoked on the proxy, a transaction is started,
suspended, marked as read-only, and so on, depending on the transaction configuration
associated with that method. Consider the following program that test drives the configuration
shown earlier:
Java Kotlin
JAVA
public final class Boot {
The output from running the preceding program should resemble the following (the Log4J output
and the stack trace from the UnsupportedOperationException thrown by the insertFoo(..) method
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 22/163
3/10/2020 Data Access
XML
<!-- the Spring container is starting up... -->
[AspectJInvocationContextExposingAdvisorAutoProxyCreator] - Creating implicit proxy for bean 'fo
<!-- ... the insertFoo(..) method is now being invoked on the proxy -->
[TransactionInterceptor] - Getting transaction for x.y.service.FooService.insertFoo
<!-- and the transaction is rolled back (by default, RuntimeException instances cause rollback)
[DataSourceTransactionManager] - Rolling back JDBC transaction on Connection [org.apache.commons
[DataSourceTransactionManager] - Releasing JDBC Connection after transaction
[DataSourceUtils] - Returning JDBC Connection to DataSource
The recommended way to indicate to the Spring Framework’s transaction infrastructure that a
transaction’s work is to be rolled back is to throw an Exception from code that is currently
executing in the context of a transaction. The Spring Framework’s transaction infrastructure
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 23/163
3/10/2020 Data Access
code catches any unhandled Exception as it bubbles up the call stack and makes a
determination whether to mark the transaction for rollback.
In its default configuration, the Spring Framework’s transaction infrastructure code marks a
transaction for rollback only in the case of runtime, unchecked exceptions. That is, when the
thrown exception is an instance or subclass of RuntimeException . ( Error instances also, by
default, result in a rollback). Checked exceptions that are thrown from a transactional method
do not result in rollback in the default configuration.
You can configure exactly which Exception types mark a transaction for rollback, including
checked exceptions. The following XML snippet demonstrates how you configure rollback for a
checked, application-specific Exception type:
XML
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="get*" read-only="true" rollback-for="NoProductInStockException"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
If you do not want a transaction rolled back when an exception is thrown, you can also specify 'no
rollback rules'. The following example tells the Spring Framework’s transaction infrastructure to
commit the attendant transaction even in the face of an unhandled
InstrumentNotFoundException :
XML
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="updateStock" no-rollback-for="InstrumentNotFoundException"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
When the Spring Framework’s transaction infrastructure catches an exception and it consults
the configured rollback rules to determine whether to mark the transaction for rollback, the
strongest matching rule wins. So, in the case of the following configuration, any exception other
than an InstrumentNotFoundException results in a rollback of the attendant transaction:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 24/163
3/10/2020 Data Access
XML
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*" rollback-for="Throwable" no-rollback-for="InstrumentNotFoundException"/>
</tx:attributes>
</tx:advice>
You can also indicate a required rollback programmatically. Although simple, this process is
quite invasive and tightly couples your code to the Spring Framework’s transaction
infrastructure. The following example shows how to programmatically indicate a required
rollback:
Java Kotlin
JAVA
public void resolvePosition() {
try {
// some business logic...
} catch (NoProductInStockException ex) {
// trigger rollback programmatically
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
}
}
You are strongly encouraged to use the declarative approach to rollback, if at all possible.
Programmatic rollback is available should you absolutely need it, but its usage flies in the face
of achieving a clean POJO-based architecture.
As a point of comparison, first assume that all of your service layer classes are defined in a root
x.y.service package. To make all beans that are instances of classes defined in that package
(or in subpackages) and that have names ending in Service have the default transactional
configuration, you could write the following:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 25/163
3/10/2020 Data Access
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:config>
<aop:pointcut id="serviceOperation"
expression="execution(* x.y.service..*Service.*(..))"/>
</aop:config>
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="get*" read-only="true"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
</beans>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 26/163
3/10/2020 Data Access
The following example shows how to configure two distinct beans with totally different
transactional settings:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:config>
<aop:pointcut id="defaultServiceOperation"
expression="execution(* x.y.service.*Service.*(..))"/>
<aop:pointcut id="noTxServiceOperation"
expression="execution(* x.y.service.ddl.DefaultDdlManager.*(..))"/>
</aop:config>
<!-- this bean will be transactional (see the 'defaultServiceOperation' pointcut) -->
<bean id="fooService" class="x.y.service.DefaultFooService"/>
<!-- this bean will also be transactional, but with totally different transactional settings
<bean id="anotherFooService" class="x.y.service.ddl.DefaultDdlManager"/>
<tx:advice id="defaultTxAdvice">
<tx:attributes>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 27/163
3/10/2020 Data Access
<tx:advice id="noTxAdvice">
<tx:attributes>
<tx:method name="*" propagation="NEVER"/>
</tx:attributes>
</tx:advice>
</beans>
The transaction timeout defaults to the default timeout of the underlying transaction system
or none if timeouts are not supported.
Any RuntimeException triggers rollback, and any checked Exception does not.
You can change these default settings. The following table summarizes the various attributes of
the <tx:method/> tags that are nested within <tx:advice/> and <tx:attributes/> tags:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 28/163
3/10/2020 Data Access
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 29/163
3/10/2020 Data Access
rollback-for No Comma-delimited
list of Exception
instances that
trigger rollback. For
example,
com.foo.MyBusinessEx
ception,ServletExcep
tion .
no-rollback-for No Comma-delimited
list of Exception
instances that do
not trigger rollback.
For example,
com.foo.MyBusinessEx
ception,ServletExcep
tion .
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 30/163
3/10/2020 Data Access
The ease-of-use afforded by the use of the @Transactional annotation is best illustrated with an
example, which is explained in the text that follows. Consider the following class definition:
Java Kotlin
JAVA
// the service class that we want to make transactional
@Transactional
public class DefaultFooService implements FooService {
Used at the class level as above, the annotation indicates a default for all methods of the
declaring class (as well as its subclasses). Alternatively, each method can get annotated
individually. Note that a class-level annotation does not apply to ancestor classes up the class
hierarchy; in such a scenario, methods need to be locally redeclared in order to participate in a
subclass-level annotation.
When a POJO class such as the one above is defined as a bean in a Spring context, you can make
the bean instance transactional through an @EnableTransactionManagement annotation in a
@Configuration class. See the javadoc for full details.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 31/163
3/10/2020 Data Access
XML
<!-- from the file 'context.xml' -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- this is the service object that we want to make transactional -->
<bean id="fooService" class="x.y.service.DefaultFooService"/>
</beans>
You can omit the transaction-manager attribute in the <tx:annotation-driven/> tag if the
bean name of the PlatformTransactionManager that you want to wire in has the name,
transactionManager . If the PlatformTransactionManager bean that you want to dependency-
inject has any other name, you have to use the transaction-manager attribute, as in the
preceding example.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 32/163
3/10/2020 Data Access
The Spring team recommends that you annotate only concrete classes (and methods of
concrete classes) with the @Transactional annotation, as opposed to annotating interfaces.
You certainly can place the @Transactional annotation on an interface (or an interface
method), but this works only as you would expect it to if you use interface-based proxies.
The fact that Java annotations are not inherited from interfaces means that, if you use
class-based proxies ( proxy-target-class="true" ) or the weaving-based aspect
( mode="aspectj" ), the transaction settings are not recognized by the proxying and weaving
infrastructure, and the object is not wrapped in a transactional proxy.
In proxy mode (which is the default), only external method calls coming in through the
proxy are intercepted. This means that self-invocation (in effect, a method within the target
object calling another method of the target object) does not lead to an actual transaction
at runtime even if the invoked method is marked with @Transactional . Also, the proxy must
be fully initialized to provide the expected behavior, so you should not rely on this feature
in your initialization code (that is, @PostConstruct ).
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 33/163
3/10/2020 Data Access
Consider using of AspectJ mode (see the mode attribute in the following table) if you expect self-
invocations to be wrapped with transactions as well. In this case, there no proxy in the first
place. Instead, the target class is woven (that is, its byte code is modified) to turn
@Transactional into runtime behavior on any kind of method.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 34/163
3/10/2020 Data Access
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 35/163
3/10/2020 Data Access
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 36/163
3/10/2020 Data Access
The default advice mode for processing @Transactional annotations is proxy , which allows
for interception of calls through the proxy only. Local calls within the same class cannot get
intercepted that way. For a more advanced mode of interception, consider switching to
aspectj mode in combination with compile-time or load-time weaving.
The proxy-target-class attribute controls what type of transactional proxies are created
for classes annotated with the @Transactional annotation. If proxy-target-class is set to
true , class-based proxies are created. If proxy-target-class is false or if the attribute is
omitted, standard JDK interface-based proxies are created. (See core.html for a discussion
of the different proxy types.)
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 37/163
3/10/2020 Data Access
The most derived location takes precedence when evaluating the transactional settings for a
method. In the case of the following example, the DefaultFooService class is annotated at the
class level with the settings for a read-only transaction, but the @Transactional annotation on
the updateFoo(Foo) method in the same class takes precedence over the transactional settings
defined at the class level.
Java Kotlin
JAVA
@Transactional(readOnly = true)
public class DefaultFooService implements FooService {
@Transactional Settings
The @Transactional annotation is metadata that specifies that an interface, class, or method
must have transactional semantics (for example, “start a brand new read-only transaction when
this method is invoked, suspending any existing transaction”). The default @Transactional
settings are as follows:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 38/163
3/10/2020 Data Access
The transaction timeout defaults to the default timeout of the underlying transaction system,
or to none if timeouts are not supported.
Any RuntimeException triggers rollback, and any checked Exception does not.
You can change these default settings. The following table summarizes the various properties of
the @Transactional annotation:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 39/163
3/10/2020 Data Access
Currently, you cannot have explicit control over the name of a transaction, where 'name' means
the transaction name that appears in a transaction monitor, if applicable (for example,
WebLogic’s transaction monitor), and in logging output. For declarative transactions, the
transaction name is always the fully-qualified class name + . + the method name of the
transactionally advised class. For example, if the handlePayment(..) method of the
BusinessService class started a transaction, the name of the transaction would be:
com.example.BusinessService.handlePayment .
Java Kotlin
JAVA
public class TransactionalService {
@Transactional("order")
public void setSomething(String name) { ... }
@Transactional("account")
public void doSomething() { ... }
}
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 40/163
3/10/2020 Data Access
XML
<tx:annotation-driven/>
In this case, the two methods on TransactionalService run under separate transaction
managers, differentiated by the order and account qualifiers. The default <tx:annotation-
driven> target bean name, transactionManager , is still used if no specifically qualified
PlatformTransactionManager bean is found.
Java Kotlin
JAVA
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("order")
public @interface OrderTx {
}
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Transactional("account")
public @interface AccountTx {
}
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 41/163
3/10/2020 Data Access
The preceding annotations lets us write the example from the previous section as follows:
Java Kotlin
JAVA
public class TransactionalService {
@OrderTx
public void setSomething(String name) {
// ...
}
@AccountTx
public void doSomething() {
// ...
}
}
In the preceding example, we used the syntax to define the transaction manager qualifier, but we
could also have included propagation behavior, rollback rules, timeouts, and other features.
Understanding PROPAGATION_REQUIRED
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 42/163
3/10/2020 Data Access
PROPAGATION_REQUIRED enforces a physical transaction, either locally for the current scope if no
transaction exists yet or participating in an existing 'outer' transaction defined for a larger
scope. This is a fine default in common call stack arrangements within the same thread (for
example, a service facade that delegates to several repository methods where all the underlying
resources have to participate in the service-level transaction).
By default, a participating transaction joins the characteristics of the outer scope, silently
ignoring the local isolation level, timeout value, or read-only flag (if any). Consider
switching the validateExistingTransactions flag to true on your transaction manager if
you want isolation level declarations to be rejected when participating in an existing
transaction with a different isolation level. This non-lenient mode also rejects read-only
mismatches (that is, an inner read-write transaction that tries to participate in a read-only
outer scope).
When the propagation setting is PROPAGATION_REQUIRED , a logical transaction scope is created for
each method upon which the setting is applied. Each such logical transaction scope can
determine rollback-only status individually, with an outer transaction scope being logically
independent from the inner transaction scope. In the case of standard PROPAGATION_REQUIRED
behavior, all these scopes are mapped to the same physical transaction. So a rollback-only
marker set in the inner transaction scope does affect the outer transaction’s chance to actually
commit.
However, in the case where an inner transaction scope sets the rollback-only marker, the outer
transaction has not decided on the rollback itself, so the rollback (silently triggered by the inner
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 43/163
3/10/2020 Data Access
Understanding PROPAGATION_REQUIRES_NEW
Understanding PROPAGATION_NESTED
PROPAGATION_NESTED uses a single physical transaction with multiple savepoints that it can roll
back to. Such partial rollbacks let an inner transaction scope trigger a rollback for its scope, with
the outer transaction being able to continue the physical transaction despite some operations
having been rolled back. This setting is typically mapped onto JDBC savepoints, so it works only
with JDBC resource transactions. See Spring’s DataSourceTransactionManager .
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 44/163
3/10/2020 Data Access
Suppose you want to execute both transactional operations and some basic profiling advice.
How do you effect this in the context of <tx:annotation-driven/> ?
When you invoke the updateFoo(Foo) method, you want to see the following actions:
The profiling aspect reports the exact duration of the whole transactional method invocation.
This chapter is not concerned with explaining AOP in any great detail (except as it applies
to transactions). See AOP for detailed coverage of the AOP configuration and AOP in general.
The following code shows the simple profiling aspect discussed earlier:
Java Kotlin
JAVA
package x.y;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.util.StopWatch;
import org.springframework.core.Ordered;
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 45/163
3/10/2020 Data Access
The ordering of advice is controlled through the Ordered interface. For full details on advice
ordering, see Advice ordering.
The following configuration creates a fooService bean that has profiling and transactional
aspects applied to it in the desired order:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:config>
<!-- this advice will execute around the transactional advice -->
<aop:aspect id="profilingAspect" ref="profiler">
<aop:pointcut id="serviceMethodWithReturnValue"
expression="execution(!void x.y..*Service.*(..))"/>
<aop:around method="profile" pointcut-ref="serviceMethodWithReturnValue"/>
</aop:aspect>
</aop:config>
</beans>
The following example creates the same setup as the previous two examples but uses the purely
XML declarative approach:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 47/163
3/10/2020 Data Access
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<aop:config>
<aop:pointcut id="entryPointMethod" expression="execution(* x.y..*Service.*(..))"/>
<!-- will execute after the profiling advice (c.f. the order attribute) -->
</aop:config>
</beans>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 48/163
3/10/2020 Data Access
The result of the preceding configuration is a fooService bean that has profiling and
transactional aspects applied to it in that order. If you want the profiling advice to execute after
the transactional advice on the way in and before the transactional advice on the way out, you
can swap the value of the profiling aspect bean’s order property so that it is higher than the
transactional advice’s order value.
Prior to continuing, you may want to read Using @Transactional and AOP respectively.
The following example shows how to create a transaction manager and configure the
AnnotationTransactionAspect to use it:
Java Kotlin
JAVA
// construct an appropriate transaction manager
DataSourceTransactionManager txManager = new DataSourceTransactionManager(getDataSource());
// configure the AnnotationTransactionAspect to use it; this must be done before executing any t
AnnotationTransactionAspect.aspectOf().setTransactionManager(txManager);
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 49/163
3/10/2020 Data Access
When you use this aspect, you must annotate the implementation class (or the methods
within that class or both), not the interface (if any) that the class implements. AspectJ
follows Java’s rule that annotations on interfaces are not inherited.
The @Transactional annotation on a class specifies the default transaction semantics for the
execution of any public method in the class.
The @Transactional annotation on a method within the class overrides the default transaction
semantics given by the class annotation (if present). You can annotate any method, regardless of
visibility.
To weave your applications with the AnnotationTransactionAspect , you must either build your
application with AspectJ (see the AspectJ Development Guide) or use load-time weaving. See
Load-time weaving with AspectJ in the Spring Framework for a discussion of load-time weaving
with AspectJ.
The TransactionTemplate .
The Spring team generally recommends the TransactionTemplate for programmatic transaction
management. The second approach is similar to using the JTA UserTransaction API, although
exception handling is less cumbersome.
As the examples that follow show, using the TransactionTemplate absolutely couples you to
Spring’s transaction infrastructure and APIs. Whether or not programmatic transaction
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 50/163
3/10/2020 Data Access
management is suitable for your development needs is a decision that you have to make
yourself.
Application code that must execute in a transactional context and that explicitly uses the
TransactionTemplate resembles the next example. You, as an application developer, can write a
TransactionCallback implementation (typically expressed as an anonymous inner class) that
contains the code that you need to execute in the context of a transaction. You can then pass an
instance of your custom TransactionCallback to the execute(..) method exposed on the
TransactionTemplate . The following example shows how to do so:
Java Kotlin
JAVA
public class SimpleService implements Service {
If there is no return value, you can use the convenient TransactionCallbackWithoutResult class
with an anonymous class, as follows:
Java Kotlin
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 51/163
3/10/2020 Data Access
JAVA
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
protected void doInTransactionWithoutResult(TransactionStatus status) {
updateOperation1();
updateOperation2();
}
});
Code within the callback can roll the transaction back by calling the setRollbackOnly() method
on the supplied TransactionStatus object, as follows:
Java Kotlin
JAVA
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
Java Kotlin
JAVA
public class SimpleService implements Service {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 52/163
3/10/2020 Data Access
The following example defines a TransactionTemplate with some custom transactional settings
by using Spring XML configuration:
XML
<bean id="sharedTransactionTemplate"
class="org.springframework.transaction.support.TransactionTemplate">
<property name="isolationLevelName" value="ISOLATION_READ_UNCOMMITTED"/>
<property name="timeout" value="30"/>
</bean>
You can then inject the sharedTransactionTemplate into as many services as are required.
Finally, instances of the TransactionTemplate class are thread-safe, in that instances do not
maintain any conversational state. TransactionTemplate instances do, however, maintain
configuration state. So, while a number of classes may share a single instance of a
TransactionTemplate , if a class needs to use a TransactionTemplate with different settings (for
example, a different isolation level), you need to create two distinct TransactionTemplate
instances.
Java Kotlin
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 53/163
3/10/2020 Data Access
JAVA
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
// explicitly setting the transaction name is something that can be done only programmatically
def.setName("SomeTxName");
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
On the other hand, if your application has numerous transactional operations, declarative
transaction management is usually worthwhile. It keeps transaction management out of
business logic and is not difficult to configure. When using the Spring Framework, rather than
EJB CMT, the configuration cost of declarative transaction management is greatly reduced.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 54/163
3/10/2020 Data Access
You can register a regular event listener by using the @EventListener annotation. If you need to
bind it to the transaction, use @TransactionalEventListener . When you do so, the listener is
bound to the commit phase of the transaction by default.
The next example shows this concept. Assume that a component publishes an order-created
event and that we want to define a listener that should only handle that event once the
transaction in which it has been published has committed successfully. The following example
sets up such an event listener:
Java Kotlin
JAVA
@Component
public class MyComponent {
@TransactionalEventListener
public void handleOrderCreatedEvent(CreationEvent<Order> creationEvent) {
// ...
}
}
The @TransactionalEventListener annotation exposes a phase attribute that lets you customize
the phase of the transaction to which the listener should be bound. The valid phases are
BEFORE_COMMIT , AFTER_COMMIT (default), AFTER_ROLLBACK , and AFTER_COMPLETION that aggregates
the transaction completion (be it a commit or a rollback).
If no transaction is running, the listener is not invoked at all, since we cannot honor the required
semantics. You can, however, override that behavior by setting the fallbackExecution attribute of
the annotation to true .
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 55/163
3/10/2020 Data Access
Spring’s JtaTransactionManager is the standard choice to run on Java EE application servers and
is known to work on all common servers. Advanced functionality, such as transaction
suspension, works on many servers as well (including GlassFish, JBoss and Geronimo) without
any special configuration required. However, for fully supported transaction suspension and
further advanced integration, Spring includes special adapters for WebLogic Server and
WebSphere. These adapters are discussed in the following sections.
For standard scenarios, including WebLogic Server and WebSphere, consider using the
convenient <tx:jta-transaction-manager/> configuration element. When configured, this element
automatically detects the underlying server and chooses the best transaction manager available
for the platform. This means that you need not explicitly configure server-specific adapter
classes (as discussed in the following sections). Rather, they are chosen automatically, with the
standard JtaTransactionManager as the default fallback.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 56/163
3/10/2020 Data Access
Java Transaction Design Strategies is a book available from InfoQ that provides a well-paced
introduction to transactions in Java. It also includes side-by-side examples of how to
configure and use transactions with both the Spring Framework and EJB3.
2. DAO Support
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data
access technologies (such as JDBC, Hibernate, or JPA) in a consistent way. This lets you switch
between the aforementioned persistence technologies fairly easily, and it also lets you code
without worrying about catching exceptions that are specific to each technology.
In addition to JDBC exceptions, Spring can also wrap JPA- and Hibernate-specific exceptions,
converting them to a set of focused runtime exceptions. This lets you handle most non-
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 57/163
3/10/2020 Data Access
recoverable persistence exceptions in only the appropriate layers, without having annoying
boilerplate catch-and-throw blocks and exception declarations in your DAOs. (You can still trap
and handle exceptions anywhere you need to though.) As mentioned above, JDBC exceptions
(including database-specific dialects) are also converted to the same hierarchy, meaning that
you can perform some operations with JDBC within a consistent programming model.
The preceding discussion holds true for the various template classes in Spring’s support for
various ORM frameworks. If you use the interceptor-based classes, the application must care
about handling HibernateExceptions and PersistenceExceptions itself, preferably by delegating
to the convertHibernateAccessException(..) or convertJpaAccessException() methods,
respectively, of SessionFactoryUtils . These methods convert the exceptions to exceptions that
are compatible with the exceptions in the org.springframework.dao exception hierarchy. As
PersistenceExceptions are unchecked, they can get thrown, too (sacrificing generic DAO
abstraction in terms of exceptions, though).
The following image shows the exception hierarchy that Spring provides. (Note that the class
hierarchy detailed in the image shows only a subset of the entire DataAccessException hierarchy.)
Java Kotlin
JAVA
@Repository 1
Any DAO or repository implementation needs access to a persistence resource, depending on the
persistence technology used. For example, a JDBC-based repository needs access to a JDBC
DataSource , and a JPA-based repository needs access to an EntityManager . The easiest way to
accomplish this is to have this resource dependency injected by using one of the @Autowired ,
@Inject , @Resource or @PersistenceContext annotations. The following example works for a JPA
repository:
Java Kotlin
JAVA
@Repository
public class JpaMovieFinder implements MovieFinder {
@PersistenceContext
private EntityManager entityManager;
// ...
}
If you use the classic Hibernate APIs, you can inject SessionFactory , as the following example
shows:
Java Kotlin
JAVA
@Repository
public class HibernateMovieFinder implements MovieFinder {
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 59/163
3/10/2020 Data Access
this.sessionFactory = sessionFactory;
}
// ...
}
The last example we show here is for typical JDBC support. You could have the DataSource
injected into an initialization method or a constructor, where you would create a JdbcTemplate
and other data access support classes (such as SimpleJdbcCall and others) by using this
DataSource . The following example autowires a DataSource :
Java Kotlin
JAVA
@Repository
public class JdbcMovieFinder implements MovieFinder {
@Autowired
public void init(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
// ...
}
See the specific coverage of each persistence technology for details on how to configure
the application context to take advantage of these annotations.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 60/163
3/10/2020 Data Access
Define connection X
parameters.
Handle transactions. X
The Spring Framework takes care of all the low-level details that can make JDBC such a tedious
API.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 61/163
3/10/2020 Data Access
can still mix and match to include a feature from a different approach. All approaches require a
JDBC 2.0-compliant driver, and some advanced features require a JDBC 3.0 driver.
JdbcTemplate is the classic and most popular Spring JDBC approach. This “lowest-level”
approach and all others use a JdbcTemplate under the covers.
core : The org.springframework.jdbc.core package contains the JdbcTemplate class and its
various callback interfaces, plus a variety of related classes. A subpackage named
org.springframework.jdbc.core.simple contains the SimpleJdbcInsert and SimpleJdbcCall
classes. Another subpackage named org.springframework.jdbc.core.namedparam contains the
NamedParameterJdbcTemplate class and the related support classes. See Using the JDBC Core
Classes to Control Basic JDBC Processing and Error Handling, JDBC Batch Operations, and
Simplifying JDBC Operations with the SimpleJdbc Classes.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 62/163
3/10/2020 Data Access
Using JdbcTemplate
Using NamedParameterJdbcTemplate
Using SQLExceptionTranslator
Running Statements
Running Queries
Performs iteration over ResultSet instances and extraction of returned parameter values.
Catches JDBC exceptions and translates them to the generic, more informative, exception
hierarchy defined in the org.springframework.dao package. (See Consistent Exception
Hierarchy.)
When you use the JdbcTemplate for your code, you need only to implement callback interfaces,
giving them a clearly defined contract. Given a Connection provided by the JdbcTemplate class,
the PreparedStatementCreator callback interface creates a prepared statement, providing SQL
and any necessary parameters. The same is true for the CallableStatementCreator interface,
which creates callable statements. The RowCallbackHandler interface extracts values from each
row of a ResultSet .
You can use JdbcTemplate within a DAO implementation through direct instantiation with a
DataSource reference, or you can configure it in a Spring IoC container and give it to DAOs as a
bean reference.
The DataSource should always be configured as a bean in the Spring IoC container. In the
first case the bean is given to the service directly; in the second case it is given to the
prepared template.
All SQL issued by this class is logged at the DEBUG level under the category corresponding to the
fully qualified class name of the template instance (typically JdbcTemplate , but it may be
different if you use a custom subclass of the JdbcTemplate class).
The following sections provide some examples of JdbcTemplate usage. These examples are not
an exhaustive list of all of the functionality exposed by the JdbcTemplate . See the attendant
javadoc for that.
Querying ( SELECT )
The following query gets the number of rows in a relation:
Java Kotlin
JAVA
int rowCount = this.jdbcTemplate.queryForObject("select count(*) from t_actor", Integer.class);
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 64/163
3/10/2020 Data Access
Java Kotlin
JAVA
int countOfActorsNamedJoe = this.jdbcTemplate.queryForObject(
"select count(*) from t_actor where first_name = ?", Integer.class, "Joe");
Java Kotlin
JAVA
String lastName = this.jdbcTemplate.queryForObject(
"select last_name from t_actor where id = ?",
new Object[]{1212L}, String.class);
Java Kotlin
JAVA
Actor actor = this.jdbcTemplate.queryForObject(
"select first_name, last_name from t_actor where id = ?",
new Object[]{1212L},
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
Java Kotlin
JAVA
List<Actor> actors = this.jdbcTemplate.query(
"select first_name, last_name from t_actor",
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 65/163
3/10/2020 Data Access
new RowMapper<Actor>() {
public Actor mapRow(ResultSet rs, int rowNum) throws SQLException {
Actor actor = new Actor();
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
});
If the last two snippets of code actually existed in the same application, it would make sense to
remove the duplication present in the two RowMapper anonymous inner classes and extract them
out into a single class (typically a static nested class) that could then be referenced by DAO
methods as needed. For example, it may be better to write the preceding code snippet as follows:
Java Kotlin
JAVA
public List<Actor> findAllActors() {
return this.jdbcTemplate.query( "select first_name, last_name from t_actor", new ActorMapper
}
Java Kotlin
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 66/163
3/10/2020 Data Access
JAVA
this.jdbcTemplate.update(
"insert into t_actor (first_name, last_name) values (?, ?)",
"Leonor", "Watling");
Java Kotlin
JAVA
this.jdbcTemplate.update(
"update t_actor set last_name = ? where id = ?",
"Banjo", 5276L);
Java Kotlin
JAVA
this.jdbcTemplate.update(
"delete from actor where id = ?",
Long.valueOf(actorId));
Java Kotlin
JAVA
this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
Java Kotlin
JAVA
this.jdbcTemplate.update(
"call SUPPORT.REFRESH_ACTORS_SUMMARY(?)",
Long.valueOf(unionId));
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 67/163
3/10/2020 Data Access
Instances of the JdbcTemplate class are thread-safe, once configured. This is important because
it means that you can configure a single instance of a JdbcTemplate and then safely inject this
shared reference into multiple DAOs (or repositories). The JdbcTemplate is stateful, in that it
maintains a reference to a DataSource , but this state is not conversational state.
A common practice when using the JdbcTemplate class (and the associated
NamedParameterJdbcTemplate class) is to configure a DataSource in your Spring configuration file
and then dependency-inject that shared DataSource bean into your DAO classes. The
JdbcTemplate is created in the setter for the DataSource . This leads to DAOs that resemble the
following:
Java Kotlin
JAVA
public class JdbcCorporateEventDao implements CorporateEventDao {
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 68/163
3/10/2020 Data Access
https://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="jdbc.properties"/>
</beans>
Java Kotlin
JAVA
@Repository 1
public class JdbcCorporateEventDao implements CorporateEventDao {
@Autowired 2
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource); 3
3
Create a new JdbcTemplate with the DataSource .
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- Scans within the base package of the application for @Component classes to configure as
<context:component-scan base-package="org.springframework.docs.test" />
<context:property-placeholder location="jdbc.properties"/>
</beans>
If you use Spring’s JdbcDaoSupport class and your various JDBC-backed DAO classes extend from
it, your sub-class inherits a setDataSource(..) method from the JdbcDaoSupport class. You can
choose whether to inherit from this class. The JdbcDaoSupport class is provided as a convenience
only.
Regardless of which of the above template initialization styles you choose to use (or not), it is
seldom necessary to create a new instance of a JdbcTemplate class each time you want to run
SQL. Once configured, a JdbcTemplate instance is thread-safe. If your application accesses
multiple databases, you may want multiple JdbcTemplate instances, which requires multiple
DataSources and, subsequently, multiple differently configured JdbcTemplate instances.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 70/163
3/10/2020 Data Access
Java Kotlin
JAVA
// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
Notice the use of the named parameter notation in the value assigned to the sql variable and
the corresponding value that is plugged into the namedParameters variable (of type
MapSqlParameterSource ).
Alternatively, you can pass along named parameters and their corresponding values to a
NamedParameterJdbcTemplate instance by using the Map -based style.The remaining methods
exposed by the NamedParameterJdbcOperations and implemented by the
NamedParameterJdbcTemplate class follow a similar pattern and are not covered here.
The following example shows the use of the Map -based style:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 71/163
3/10/2020 Data Access
Java Kotlin
JAVA
// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
One nice feature related to the NamedParameterJdbcTemplate (and existing in the same Java
package) is the SqlParameterSource interface. You have already seen an example of an
implementation of this interface in one of the previous code snippets (the
MapSqlParameterSource class). An SqlParameterSource is a source of named parameter values to a
NamedParameterJdbcTemplate . The MapSqlParameterSource class is a simple implementation that is
an adapter around a java.util.Map , where the keys are the parameter names and the values are
the parameter values.
Java Kotlin
JAVA
public class Actor {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 72/163
3/10/2020 Data Access
// setters omitted...
The following example uses a NamedParameterJdbcTemplate to return the count of the members of
the class shown in the preceding example:
Java Kotlin
JAVA
// some JDBC-backed DAO class...
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
// notice how the named parameters match the properties of the above 'Actor' class
String sql = "select count(*) from T_ACTOR where first_name = :firstName and last_name = :la
See also JdbcTemplate Best Practices for guidelines on using the NamedParameterJdbcTemplate
class in the context of an application.
SQLStateSQLExceptionTranslator .
The SQLErrorCodesFactory is used by default to define Error codes and custom exception
translations. They are looked up in a file named sql-error-codes.xml from the classpath,
and the matching SQLErrorCodes instance is located based on the database name from the
database metadata of the database in use.
Java Kotlin
JAVA
public class CustomSQLErrorCodesTranslator extends SQLErrorCodeSQLExceptionTranslator {
In the preceding example, the specific error code ( -12345 ) is translated, while other errors are
left to be translated by the default translator implementation. To use this custom translator, you
must pass it to the JdbcTemplate through the method setExceptionTranslator , and you must use
this JdbcTemplate for all of the data access processing where this translator is needed. The
following example shows how you can use this custom translator:
Java Kotlin
JAVA
private JdbcTemplate jdbcTemplate;
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 75/163
3/10/2020 Data Access
// create a custom translator and set the DataSource for the default translation lookup
CustomSQLErrorCodesTranslator tr = new CustomSQLErrorCodesTranslator();
tr.setDataSource(dataSource);
this.jdbcTemplate.setExceptionTranslator(tr);
The custom translator is passed a data source in order to look up the error codes in sql-error-
codes.xml .
Java Kotlin
JAVA
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 76/163
3/10/2020 Data Access
Java Kotlin
JAVA
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
In addition to the single result query methods, several methods return a list with an entry for
each row that the query returned. The most generic method is queryForList(..) , which returns a
List where each element is a Map containing one entry for each column, using the column
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 77/163
3/10/2020 Data Access
name as the key. If you add a method to the preceding example to retrieve a list of all the rows, it
might be as follows:
Java Kotlin
JAVA
private JdbcTemplate jdbcTemplate;
Java Kotlin
JAVA
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 78/163
3/10/2020 Data Access
}
}
In the preceding example, an SQL statement has placeholders for row parameters. You can pass
the parameter values in as varargs or ,alternatively, as an array of objects. Thus, you should
explicitly wrap primitives in the primitive wrapper classes, or you should use auto-boxing.
Java Kotlin
JAVA
final String INSERT_SQL = "insert into my_test (name) values(?)";
final String name = "Rob";
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 79/163
3/10/2020 Data Access
Using DataSource
Using DataSourceUtils
Implementing SmartDataSource
Extending AbstractDataSource
Using SingleConnectionDataSource
Using DriverManagerDataSource
Using TransactionAwareDataSourceProxy
Using DataSourceTransactionManager
When you use Spring’s JDBC layer, you can obtain a data source from JNDI, or you can configure
your own with a connection pool implementation provided by a third party. Traditional choices
are Apache Commons DBCP and C3P0 with bean-style DataSource classes; for a modern JDBC
connection pool, consider HikariCP with its builder-style API instead.
To configure a DriverManagerDataSource :
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 80/163
3/10/2020 Data Access
2. Specify the fully qualified classname of the JDBC driver so that the DriverManager can load
the driver class.
3. Provide a URL that varies between JDBC drivers. (See the documentation for your driver for
the correct value.)
Java Kotlin
JAVA
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
dataSource.setUrl("jdbc:hsqldb:hsql://localhost:");
dataSource.setUsername("sa");
dataSource.setPassword("");
XML
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>
The next two examples show the basic connectivity and configuration for DBCP and C3P0. To
learn about more options that help control the pooling features, see the product documentation
for the respective connection pooling implementations.
XML
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 81/163
3/10/2020 Data Access
<context:property-placeholder location="jdbc.properties"/>
XML
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 82/163
3/10/2020 Data Access
If any client code calls close on the assumption of a pooled connection (as when using
persistence tools), you should set the suppressClose property to true . This setting returns a
close-suppressing proxy that wraps the physical connection. Note that you can no longer cast
this to a native Oracle Connection or a similar object.
SingleConnectionDataSource is primarily a test class. For example, it enables easy testing of code
outside an application server, in conjunction with a simple JNDI environment. In contrast to
DriverManagerDataSource , it reuses the same connection all the time, avoiding excessive creation
of physical connections.
This implementation is useful for test and stand-alone environments outside of a Java EE
container, either as a DataSource bean in a Spring IoC container or in conjunction with a simple
JNDI environment. Pool-assuming Connection.close() calls close the connection, so any
DataSource -aware persistence code should work. However, using JavaBean-style connection
pools (such as commons-dbcp ) is so easy, even in a test environment, that it is almost always
preferable to use such a connection pool over DriverManagerDataSource .
It is rarely desirable to use this class, except when already existing code must be called
and passed a standard JDBC DataSource interface implementation. In this case, you can
still have this code be usable and, at the same time, have this code participating in Spring
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 83/163
3/10/2020 Data Access
managed transactions. It is generally preferable to write your own new code by using the
higher level abstractions for resource management, such as JdbcTemplate or
DataSourceUtils .
The DataSourceTransactionManager class supports custom isolation levels and timeouts that get
applied as appropriate JDBC statement query timeouts. To support the latter, application code
must either use JdbcTemplate or call the DataSourceUtils.applyTransactionTimeout(..) method
for each created statement.
You can use this implementation instead of JtaTransactionManager in the single-resource case,
as it does not require the container to support JTA. Switching between both is just a matter of
configuration, provided you stick to the required connection lookup pattern. JTA does not
support custom isolation levels.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 84/163
3/10/2020 Data Access
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
If you process a stream of updates or reading from a file, you might have a preferred batch size,
but the last batch might not have that number of entries. In this case, you can use the
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 85/163
3/10/2020 Data Access
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
For an SQL statement that uses the classic ? placeholders, you pass in a list containing an
object array with the update values. This object array must have one entry for each placeholder
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 86/163
3/10/2020 Data Access
in the SQL statement, and they must be in the same order as they are defined in the SQL
statement.
The following example is the same as the preceding example, except that it uses classic JDBC ?
placeholders:
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
All of the batch update methods that we described earlier return an int array containing the
number of affected rows for each batch entry. This count is reported by the JDBC driver. If the
count is not available, the JDBC driver returns a value of -2 .
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 87/163
3/10/2020 Data Access
Alternatively, you might consider specifying the corresponding JDBC types explicitly, either
through a 'BatchPreparedStatementSetter' (as shown earlier), through an explicit type array
given to a 'List<Object[]>' based call, through 'registerSqlType' calls on a custom
'MapSqlParameterSource' instance, or through a 'BeanPropertySqlParameterSource' that
derives the SQL type from the Java-declared property type even for a null value.
The following example shows a batch update that uses a batch size of 100:
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 88/163
3/10/2020 Data Access
actors,
100,
new ParameterizedPreparedStatementSetter<Actor>() {
public void setValues(PreparedStatement ps, Actor argument) throws SQLExcept
ps.setString(1, argument.getFirstName());
ps.setString(2, argument.getLastName());
ps.setLong(3, argument.getId().longValue());
}
});
return updateCounts;
}
The batch update methods for this call returns an array of int arrays that contain an array entry
for each batch with an array of the number of affected rows for each update. The top level array’s
length indicates the number of batches executed and the second level array’s length indicates
the number of updates in that batch. The number of updates in each batch should be the batch
size provided for all batches (except that the last one that might be less), depending on the total
number of update objects provided. The update count for each update statement is the one
reported by the JDBC driver. If the count is not available, the JDBC driver returns a value of -2 .
style that returns the instance of the SimpleJdbcInsert , which lets you chain all configuration
methods. The following example uses only one configuration method (we show examples of
multiple methods later):
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
The execute method used here takes a plain java.util.Map as its only parameter. The important
thing to note here is that the keys used for the Map must match the column names of the table,
as defined in the database. This is because we read the metadata to construct the actual insert
statement.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 90/163
3/10/2020 Data Access
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
The main difference when you run the insert by using this second approach is that you do not
add the id to the Map , and you call the executeAndReturnKey method. This returns a
java.lang.Number object with which you can create an instance of the numerical type that is
used in your domain class. You cannot rely on all databases to return a specific Java class here.
java.lang.Number is the base class that you can rely on. If you have multiple auto-generated
columns or the generated values are non-numeric, you can use a KeyHolder that is returned
from the executeAndReturnKeyHolder method.
Java Kotlin
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 91/163
3/10/2020 Data Access
JAVA
public class JdbcActorDao implements ActorDao {
The execution of the insert is the same as if you had relied on the metadata to determine which
columns to use.
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
Another option is the MapSqlParameterSource that resembles a Map but provides a more
convenient addValue method that can be chained. The following example shows how to use it:
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 93/163
3/10/2020 Data Access
As you can see, the configuration is the same. Only the executing code has to change to use
these alternative input classes.
SQL
CREATE PROCEDURE read_actor (
IN in_id INTEGER,
OUT out_first_name VARCHAR(100),
OUT out_last_name VARCHAR(100),
OUT out_birth_date DATE)
BEGIN
SELECT first_name, last_name, birth_date
INTO out_first_name, out_last_name, out_birth_date
FROM t_actor where id = in_id;
END;
The in_id parameter contains the id of the actor that you are looking up. The out parameters
return the data read from the table.
You can declare SimpleJdbcCall in a manner similar to declaring SimpleJdbcInsert . You should
instantiate and configure the class in the initialization method of your data-access layer.
Compared to the StoredProcedure class, you need not create a subclass and you need not to
declare parameters that can be looked up in the database metadata. The following example of a
SimpleJdbcCall configuration uses the preceding stored procedure (the only configuration
option, in addition to the DataSource , is the name of the stored procedure):
Java Kotlin
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 94/163
3/10/2020 Data Access
JAVA
public class JdbcActorDao implements ActorDao {
The code you write for the execution of the call involves creating an SqlParameterSource
containing the IN parameter. You must match the name provided for the input value with that of
the parameter name declared in the stored procedure. The case does not have to match because
you use metadata to determine how database objects should be referred to in a stored
procedure. What is specified in the source for the stored procedure is not necessarily the way it
is stored in the database. Some databases transform names to all upper case, while others use
lower case or use the case as specified.
The execute method takes the IN parameters and returns a Map that contains any out
parameters keyed by the name, as specified in the stored procedure. In this case, they are
out_first_name , out_last_name , and out_birth_date .
The last part of the execute method creates an Actor instance to use to return the data
retrieved. Again, it is important to use the names of the out parameters as they are declared in
the stored procedure. Also, the case in the names of the out parameters stored in the results
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 95/163
3/10/2020 Data Access
map matches that of the out parameter names in the database, which could vary between
databases. To make your code more portable, you should do a case-insensitive lookup or instruct
Spring to use a LinkedCaseInsensitiveMap . To do the latter, you can create your own JdbcTemplate
and set the setResultsMapCaseInsensitive property to true . Then you can pass this customized
JdbcTemplate instance into the constructor of your SimpleJdbcCall . The following example shows
this configuration:
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
By taking this action, you avoid conflicts in the case used for the names of your returned out
parameters.
Explicit declarations are necessary if the database you use is not a Spring-supported
database. Currently, Spring supports metadata lookup of stored procedure calls for the
following databases: Apache Derby, DB2, MySQL, Microsoft SQL Server, Oracle, and Sybase.
We also support metadata lookup of stored functions for MySQL, Microsoft SQL Server, and
Oracle.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 96/163
3/10/2020 Data Access
You can opt to explicitly declare one, some, or all of the parameters. The parameter metadata is
still used where you do not explicitly declare parameters. To bypass all processing of metadata
lookups for potential parameters and use only the declared parameters, you can call the method
withoutProcedureColumnMetaDataAccess as part of the declaration. Suppose that you have two or
more different call signatures declared for a database function. In this case, you call
useInParameterNames to specify the list of IN parameter names to include for a given signature.
The following example shows a fully declared procedure call and uses the information from the
preceding example:
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
The execution and end results of the two examples are the same. The second example specifies
all details explicitly rather than relying on metadata.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 97/163
3/10/2020 Data Access
Java Kotlin
JAVA
new SqlParameter("in_id", Types.NUMERIC),
new SqlOutParameter("out_first_name", Types.VARCHAR),
The first line with the SqlParameter declares an IN parameter. You can use IN parameters for both
stored procedure calls and for queries by using the SqlQuery and its subclasses (covered in
Understanding SqlQuery ).
The second line (with the SqlOutParameter ) declares an out parameter to be used in a stored
procedure call. There is also an SqlInOutParameter for InOut parameters (parameters that
provide an IN value to the procedure and that also return a value).
For IN parameters, in addition to the name and the SQL type, you can specify a scale for numeric
data or a type name for custom database types. For out parameters, you can provide a
RowMapper to handle mapping of rows returned from a REF cursor. Another option is to specify an
SqlReturnType that provides an opportunity to define customized handling of the return values.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 98/163
3/10/2020 Data Access
the corresponding string for a function call is generated. A specialized execute call
( executeFunction ) is used to execute the function, and it returns the function return value as an
object of a specified type, which means you do not have to retrieve the return value from the
results map. A similar convenience method (named executeObject ) is also available for stored
procedures that have only one out parameter. The following example (for MySQL) is based on a
stored function named get_actor_name that returns an actor’s full name:
SQL
CREATE FUNCTION get_actor_name (in_id INTEGER)
RETURNS VARCHAR(200) READS SQL DATA
BEGIN
DECLARE out_name VARCHAR(200);
SELECT concat(first_name, ' ', last_name)
INTO out_name
FROM t_actor where id = in_id;
RETURN out_name;
END;
To call this function, we again create a SimpleJdbcCall in the initialization method, as the
following example shows:
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 99/163
3/10/2020 Data Access
return name;
}
The executeFunction method used returns a String that contains the return value from the
function call.
The next example (for MySQL) uses a stored procedure that takes no IN parameters and returns
all rows from the t_actor table:
SQL
CREATE PROCEDURE read_all_actors()
BEGIN
SELECT a.id, a.first_name, a.last_name, a.birth_date FROM t_actor a;
END;
To call this procedure, you can declare the RowMapper . Because the class to which you want to
map follows the JavaBean rules, you can use a BeanPropertyRowMapper that is created by passing
in the required class to map to in the newInstance method. The following example shows how to
do so:
Java Kotlin
JAVA
public class JdbcActorDao implements ActorDao {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 100/163
3/10/2020 Data Access
The execute call passes in an empty Map , because this call does not take any parameters. The
list of actors is then retrieved from the results map and returned to the caller.
Many Spring developers believe that the various RDBMS operation classes described below
(with the exception of the StoredProcedure class) can often be replaced with straight
JdbcTemplate calls. Often, it is simpler to write a DAO method that calls a method on a
JdbcTemplate directly (as opposed to encapsulating a query as a full-blown class).
However, if you are getting measurable value from using the RDBMS operation classes, you
should continue to use these classes.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 101/163
3/10/2020 Data Access
Java Kotlin
JAVA
public class ActorMappingQuery extends MappingSqlQuery<Actor> {
@Override
protected Actor mapRow(ResultSet rs, int rowNumber) throws SQLException {
Actor actor = new Actor();
actor.setId(rs.getLong("id"));
actor.setFirstName(rs.getString("first_name"));
actor.setLastName(rs.getString("last_name"));
return actor;
}
}
The class extends MappingSqlQuery parameterized with the Actor type. The constructor for this
customer query takes a DataSource as the only parameter. In this constructor, you can call the
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 102/163
3/10/2020 Data Access
constructor on the superclass with the DataSource and the SQL that should be executed to
retrieve the rows for this query. This SQL is used to create a PreparedStatement , so it may contain
placeholders for any parameters to be passed in during execution. You must declare each
parameter by using the declareParameter method passing in an SqlParameter . The SqlParameter
takes a name, and the JDBC type as defined in java.sql.Types . After you define all parameters,
you can call the compile() method so that the statement can be prepared and later run. This
class is thread-safe after it is compiled, so, as long as these instances are created when the DAO
is initialized, they can be kept as instance variables and be reused. The following example shows
how to define such a class:
Java Kotlin
JAVA
private ActorMappingQuery actorMappingQuery;
@Autowired
public void setDataSource(DataSource dataSource) {
this.actorMappingQuery = new ActorMappingQuery(dataSource);
}
The method in the preceding example retrieves the customer with the id that is passed in as
the only parameter. Since we want only one object to be returned, we call the findObject
convenience method with the id as the parameter. If we had instead a query that returned a list
of objects and took additional parameters, we would use one of the execute methods that takes
an array of parameter values passed in as varargs. The following example shows such a method:
Java Kotlin
JAVA
public List<Actor> searchForActors(int age, String namePattern) {
List<Actor> actors = actorSearchMappingQuery.execute(age, namePattern);
return actors;
}
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 103/163
3/10/2020 Data Access
The SqlUpdate class encapsulates an SQL update. As with a query, an update object is reusable,
and, as with all RdbmsOperation classes, an update can have parameters and is defined in SQL.
This class provides a number of update(..) methods analogous to the execute(..) methods of
query objects. The SQLUpdate class is concrete. It can be subclassed — for example, to add a
custom update method. However, you do not have to subclass the SqlUpdate class, since it can
easily be parameterized by setting SQL and declaring parameters. The following example creates
a custom update method named execute :
Java Kotlin
JAVA
import java.sql.Types;
import javax.sql.DataSource;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.SqlUpdate;
/**
* @param id for the Customer to be updated
* @param rating the new value for credit rating
* @return number of rows updated
*/
public int execute(int id, int rating) {
return update(rating, id);
}
}
The inherited sql property is the name of the stored procedure in the RDBMS.
To define a parameter for the StoredProcedure class, you can use an SqlParameter or one of its
subclasses. You must specify the parameter name and SQL type in the constructor, as the
following code snippet shows:
Java Kotlin
JAVA
new SqlParameter("in_id", Types.NUMERIC),
new SqlOutParameter("out_first_name", Types.VARCHAR),
The first line (with the SqlParameter ) declares an IN parameter. You can use IN parameters both
for stored procedure calls and for queries using the SqlQuery and its subclasses (covered in
Understanding SqlQuery ).
The second line (with the SqlOutParameter ) declares an out parameter to be used in the stored
procedure call. There is also an SqlInOutParameter for InOut parameters (parameters that
provide an in value to the procedure and that also return a value).
For in parameters, in addition to the name and the SQL type, you can specify a scale for numeric
data or a type name for custom database types. For out parameters, you can provide a
RowMapper to handle mapping of rows returned from a REF cursor. Another option is to specify an
SqlReturnType that lets you define customized handling of the return values.
The next example of a simple DAO uses a StoredProcedure to call a function ( sysdate() ), which
comes with any Oracle database. To use the stored procedure functionality, you have to create a
class that extends StoredProcedure . In this example, the StoredProcedure class is an inner class.
However, if you need to reuse the StoredProcedure , you can declare it as a top-level class. This
example has no input parameters, but an output parameter is declared as a date type by using
the SqlOutParameter class. The execute() method runs the procedure and extracts the returned
date from the results Map . The results Map has an entry for each declared output parameter (in
this case, only one) by using the parameter name as the key. The following listing shows our
custom StoredProcedure class:
Java Kotlin
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 105/163
3/10/2020 Data Access
JAVA
import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;
@Autowired
public void init(DataSource dataSource) {
this.getSysdate = new GetSysdateProcedure(dataSource);
}
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 106/163
3/10/2020 Data Access
The following example of a StoredProcedure has two output parameters (in this case, Oracle REF
cursors):
Java Kotlin
JAVA
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.object.StoredProcedure;
Notice how the overloaded variants of the declareParameter(..) method that have been used in
the TitlesAndGenresStoredProcedure constructor are passed RowMapper implementation
instances. This is a very convenient and powerful way to reuse existing functionality. The next
two examples provide code for the two RowMapper implementations.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 107/163
3/10/2020 Data Access
The TitleMapper class maps a ResultSet to a Title domain object for each row in the supplied
ResultSet , as follows:
Java Kotlin
JAVA
import java.sql.ResultSet;
import java.sql.SQLException;
import com.foo.domain.Title;
import org.springframework.jdbc.core.RowMapper;
The GenreMapper class maps a ResultSet to a Genre domain object for each row in the supplied
ResultSet , as follows:
Java Kotlin
JAVA
import java.sql.ResultSet;
import java.sql.SQLException;
import com.foo.domain.Genre;
import org.springframework.jdbc.core.RowMapper;
To pass parameters to a stored procedure that has one or more input parameters in its definition
in the RDBMS, you can code a strongly typed execute(..) method that would delegate to the
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 108/163
3/10/2020 Data Access
Java Kotlin
JAVA
import java.sql.Types;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import oracle.jdbc.OracleTypes;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 109/163
3/10/2020 Data Access
Many update and query methods of the JdbcTemplate take an additional parameter in the
form of an int array. This array is used to indicate the SQL type of the corresponding
parameter by using constant values from the java.sql.Types class. Provide one entry for
each parameter.
You can use the SqlParameterValue class to wrap the parameter value that needs this
additional information. To do so, create a new instance for each value and pass in the SQL
type and the parameter value in the constructor. You can also provide an optional scale
parameter for numeric values.
For methods that work with named parameters, you can use the SqlParameterSource classes,
BeanPropertySqlParameterSource or MapSqlParameterSource . They both have methods for
registering the SQL type for any of the named parameter values.
LobCreator and LobHandler provide the following support for LOB input and output:
BLOB
CLOB
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 110/163
3/10/2020 Data Access
The next example shows how to create and insert a BLOB. Later we show how to read it back from
the database.
For this example, we assume that there is a variable, lobHandler , that is already set to an
instance of a DefaultLobHandler . You typically set this value through dependency injection.
Java Kotlin
JAVA
final File blobIn = new File("spring2004.jpg");
final InputStream blobIs = new FileInputStream(blobIn);
final File clobIn = new File("large.txt");
final InputStream clobIs = new FileInputStream(clobIn);
final InputStreamReader clobReader = new InputStreamReader(clobIs);
jdbcTemplate.execute(
"INSERT INTO lob_table (id, a_clob, a_blob) VALUES (?, ?, ?)",
new AbstractLobCreatingPreparedStatementCallback(lobHandler) { 1
blobIs.close();
clobReader.close();
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 111/163
3/10/2020 Data Access
See the documentation for the JDBC driver you use to verify that it supports streaming a
LOB without providing the content length.
Now it is time to read the LOB data from the database. Again, you use a JdbcTemplate with the
same instance variable lobHandler and a reference to a DefaultLobHandler . The following
example shows how to do so:
Java Kotlin
JAVA
List<Map<String, Object>> l = jdbcTemplate.query("select id, a_clob, a_blob from lob_table",
new RowMapper<Map<String, Object>>() {
public Map<String, Object> mapRow(ResultSet rs, int i) throws SQLException {
Map<String, Object> results = new HashMap<String, Object>();
String clobText = lobHandler.getClobAsString(rs, "a_clob"); 1
results.put("CLOB", clobText);
byte[] blobBytes = lobHandler.getBlobAsBytes(rs, "a_blob"); 2
results.put("BLOB", blobBytes);
return results;
}
});
The SQL standard allows for selecting rows based on an expression that includes a variable list
of values. A typical example would be select * from T_ACTOR where id in (1, 2, 3) . This variable
list is not directly supported for prepared statements by the JDBC standard. You cannot declare a
variable number of placeholders. You need a number of variations with the desired number of
placeholders prepared, or you need to generate the SQL string dynamically once you know how
many placeholders are required. The named parameter support provided in the
NamedParameterJdbcTemplate and JdbcTemplate takes the latter approach. You can pass in the
values as a java.util.List of primitive objects. This list is used to insert the required
placeholders and pass in the values during statement execution.
Be careful when passing in many values. The JDBC standard does not guarantee that you
can use more than 100 values for an in expression list. Various databases exceed this
number, but they usually have a hard limit for how many values are allowed. For example,
Oracle’s limit is 1000.
In addition to the primitive values in the value list, you can create a java.util.List of object
arrays. This list can support multiple expressions being defined for the in clause, such as
select * from T_ACTOR where (id, last_name) in ((1, 'Johnson'), (2, 'Harrop'\)) . This, of
course, requires that your database supports this syntax.
The SqlReturnType interface has a single method (named getTypeValue ) that must be
implemented. This interface is used as part of the declaration of an SqlOutParameter . The
following example shows returning the value of an Oracle STRUCT object of the user declared type
ITEM_TYPE :
Java Kotlin
JAVA
public class TestItemStoredProcedure extends StoredProcedure {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 113/163
3/10/2020 Data Access
You can use SqlTypeValue to pass the value of a Java object (such as TestItem ) to a stored
procedure. The SqlTypeValue interface has a single method (named createTypeValue ) that you
must implement. The active connection is passed in, and you can use it to create database-
specific objects, such as StructDescriptor instances or ArrayDescriptor instances. The
following example creates a StructDescriptor instance:
Java Kotlin
JAVA
final TestItem testItem = new TestItem(123L, "A test item",
new SimpleDateFormat("yyyy-M-d").parse("2010-12-31"));
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 114/163
3/10/2020 Data Access
}
};
You can now add this SqlTypeValue to the Map that contains the input parameters for the
execute call of the stored procedure.
Another use for the SqlTypeValue is passing in an array of values to an Oracle stored procedure.
Oracle has its own internal ARRAY class that must be used in this case, and you can use the
SqlTypeValue to create an instance of the Oracle ARRAY and populate it with values from the Java
ARRAY , as the following example shows:
Java Kotlin
JAVA
final Long[] ids = new Long[] {1L, 2L};
XML
<jdbc:embedded-database id="dataSource" generate-name="true">
<jdbc:script location="classpath:schema.sql"/>
<jdbc:script location="classpath:test-data.sql"/>
</jdbc:embedded-database>
The preceding configuration creates an embedded HSQL database that is populated with SQL
from the schema.sql and test-data.sql resources in the root of the classpath. In addition, as a
best practice, the embedded database is assigned a uniquely generated name. The embedded
database is made available to the Spring container as a bean of type javax.sql.DataSource that
can then be injected into data access objects as needed.
Java Kotlin
JAVA
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(H2)
.setScriptEncoding("UTF-8")
.ignoreFailedDrops(true)
.addScript("schema.sql")
.addScripts("user_data.sql", "country_data.sql")
.build();
db.shutdown()
See the javadoc for EmbeddedDatabaseBuilder for further details on all supported options.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 116/163
3/10/2020 Data Access
You can also use the EmbeddedDatabaseBuilder to create an embedded database by using Java
configuration, as the following example shows:
Java Kotlin
JAVA
@Configuration
public class DataSourceConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.setType(H2)
.setScriptEncoding("UTF-8")
.ignoreFailedDrops(true)
.addScript("schema.sql")
.addScripts("user_data.sql", "country_data.sql")
.build();
}
}
Using HSQL
Using H2
Using Derby
Using HSQL
Spring supports HSQL 1.8.0 and above. HSQL is the default embedded database if no type is
explicitly specified. To specify HSQL explicitly, set the type attribute of the embedded-database tag
to HSQL . If you use the builder API, call the setType(EmbeddedDatabaseType) method with
EmbeddedDatabaseType.HSQL .
Using H2
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 117/163
3/10/2020 Data Access
Spring supports the H2 database. To enable H2, set the type attribute of the embedded-database
tag to H2 . If you use the builder API, call the setType(EmbeddedDatabaseType) method with
EmbeddedDatabaseType.H2 .
Using Derby
Spring supports Apache Derby 10.5 and above. To enable Derby, set the type attribute of the
embedded-database tag to DERBY . If you use the builder API, call the setType(EmbeddedDatabaseType)
method with EmbeddedDatabaseType.DERBY .
Java Kotlin
JAVA
public class DataAccessIntegrationTestTemplate {
@BeforeEach
public void setUp() {
// creates an HSQL in-memory database populated from default scripts
// classpath:schema.sql and classpath:data.sql
db = new EmbeddedDatabaseBuilder()
.generateUniqueName(true)
.addDefaultScripts()
.build();
}
@Test
public void testDataAccess() {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 118/163
3/10/2020 Data Access
@AfterEach
public void tearDown() {
db.shutdown();
}
The root cause of such errors is the fact that Spring’s EmbeddedDatabaseFactory (used internally
by both the <jdbc:embedded-database> XML namespace element and the EmbeddedDatabaseBuilder
for Java configuration) sets the name of the embedded database to testdb if not otherwise
specified. For the case of <jdbc:embedded-database> , the embedded database is typically
assigned a name equal to the bean’s id (often, something like dataSource ). Thus, subsequent
attempts to create an embedded database do not result in a new database. Instead, the same
JDBC connection URL is reused, and attempts to create a new embedded database actually point
to an existing embedded database created from the same configuration.
To address this common issue, Spring Framework 4.2 provides support for generating unique
names for embedded databases. To enable the use of generated names, use one of the following
options.
EmbeddedDatabaseFactory.setGenerateUniqueDatabaseName()
EmbeddedDatabaseBuilder.generateUniqueName()
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 119/163
3/10/2020 Data Access
XML
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath:com/foo/sql/db-schema.sql"/>
<jdbc:script location="classpath:com/foo/sql/db-test-data.sql"/>
</jdbc:initialize-database>
The preceding example runs the two specified scripts against the database. The first script
creates a schema, and the second populates tables with a test data set. The script locations can
also be patterns with wildcards in the usual Ant style used for resources in Spring (for example,
classpath*:/com/foo/**/sql/*-data.sql ). If you use a pattern, the scripts are run in the lexical
order of their URL or filename.
The default behavior of the database initializer is to unconditionally run the provided scripts.
This may not always be what you want — for instance, if you run the scripts against a database
that already has test data in it. The likelihood of accidentally deleting data is reduced by
following the common pattern (shown earlier) of creating the tables first and then inserting the
data. The first step fails if the tables already exist.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 120/163
3/10/2020 Data Access
However, to gain more control over the creation and deletion of existing data, the XML
namespace provides a few additional options. The first is a flag to switch the initialization on
and off. You can set this according to the environment (such as pulling a boolean value from
system properties or from an environment bean). The following example gets a value from a
system property:
XML
<jdbc:initialize-database data-source="dataSource"
enabled="#{systemProperties.INITIALIZE_DATABASE}"> 1
<jdbc:script location="..."/>
</jdbc:initialize-database>
1 Get the value for enabled from a system property called INITIALIZE_DATABASE .
The second option to control what happens with existing data is to be more tolerant of failures.
To this end, you can control the ability of the initializer to ignore certain errors in the SQL it
executes from the scripts, as the following example shows:
XML
<jdbc:initialize-database data-source="dataSource" ignore-failures="DROPS">
<jdbc:script location="..."/>
</jdbc:initialize-database>
In the preceding example, we are saying that we expect that, sometimes, the scripts are run
against an empty database, and there are some DROP statements in the scripts that would,
therefore, fail. So failed SQL DROP statements will be ignored, but other failures will cause an
exception. This is useful if your SQL dialect doesn’t support DROP … IF EXISTS (or similar) but you
want to unconditionally remove all test data before re-creating it. In that case the first script is
usually a set of DROP statements, followed by a set of CREATE statements.
The ignore-failures option can be set to NONE (the default), DROPS (ignore failed drops), or ALL
(ignore all failures).
Each statement should be separated by ; or a new line if the ; character is not present at all in
the script. You can control that globally or script by script, as the following example shows:
XML
<jdbc:initialize-database data-source="dataSource" separator="@@"> 1
<jdbc:script location="classpath:com/myapp/sql/db-schema.sql" separator=";"/> 2
<jdbc:script location="classpath:com/myapp/sql/db-test-data-1.sql"/>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 121/163
3/10/2020 Data Access
<jdbc:script location="classpath:com/myapp/sql/db-test-data-2.sql"/>
</jdbc:initialize-database>
In this example, the two test-data scripts use @@ as statement separator and only the db-
schema.sql uses ; . This configuration specifies that the default separator is @@ and overrides
that default for the db-schema script.
If you need more control than you get from the XML namespace, you can use the
DataSourceInitializer directly and define it as a component in your application.
The database initializer depends on a DataSource instance and runs the scripts provided in its
initialization callback (analogous to an init-method in an XML bean definition, a @PostConstruct
method in a component, or the afterPropertiesSet() method in a component that implements
InitializingBean ). If other beans depend on the same data source and use the data source in an
initialization callback, there might be a problem because the data has not yet been initialized. A
common example of this is a cache that initializes eagerly and loads data from the database on
application startup.
To get around this issue, you have two options: change your cache initialization strategy to a
later phase or ensure that the database initializer is initialized first.
Changing your cache initialization strategy might be easy if the application is in your control
and not otherwise. Some suggestions for how to implement this include:
Make the cache initialize lazily on first usage, which improves application startup time.
Have your cache or a separate component that initializes the cache implement Lifecycle or
SmartLifecycle . When the application context starts, you can automatically start a
SmartLifecycle by setting its autoStartup flag, and you can manually start a Lifecycle by
calling ConfigurableApplicationContext.start() on the enclosing context.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 122/163
3/10/2020 Data Access
Use a Spring ApplicationEvent or similar custom observer mechanism to trigger the cache
initialization. ContextRefreshedEvent is always published by the context when it is ready for
use (after all beans have been initialized), so that is often a useful hook (this is how the
SmartLifecycle works by default).
Ensuring that the database initializer is initialized first can also be easy. Some suggestions on
how to implement this include:
Rely on the default behavior of the Spring BeanFactory , which is that beans are initialized in
registration order. You can easily arrange that by adopting the common practice of a set of
<import/> elements in XML configuration that order your application modules and ensuring
that the database and database initialization are listed first.
Separate the DataSource and the business components that use it and control their startup
order by putting them in separate ApplicationContext instances (for example, the parent
context contains the DataSource , and the child context contains the business components).
This structure is common in Spring web applications but can be more generally applied.
Spring adds significant enhancements to the ORM layer of your choice when you create data
access applications. You can leverage as much of the integration support as you wish, and you
should compare this integration effort with the cost and risk of building a similar infrastructure
in-house. You can use much of the ORM support as you would a library, regardless of technology,
because everything is designed as a set of reusable JavaBeans. ORM in a Spring IoC container
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 123/163
3/10/2020 Data Access
facilitates configuration and deployment. Thus, most examples in this section show
configuration inside a Spring container.
The benefits of using the Spring Framework to create your ORM DAOs include:
Easier testing. Spring’s IoC approach makes it easy to swap the implementations and
configuration locations of Hibernate SessionFactory instances, JDBC DataSource instances,
transaction managers, and mapped object implementations (if needed). This in turn makes it
much easier to test each piece of persistence-related code in isolation.
Common data access exceptions. Spring can wrap exceptions from your ORM tool,
converting them from proprietary (potentially checked) exceptions to a common runtime
DataAccessException hierarchy. This feature lets you handle most persistence exceptions,
which are non-recoverable, only in the appropriate layers, without annoying boilerplate
catches, throws, and exception declarations. You can still trap and handle exceptions as
necessary. Remember that JDBC exceptions (including DB-specific dialects) are also
converted to the same hierarchy, meaning that you can perform some operations with JDBC
within a consistent programming model.
General resource management. Spring application contexts can handle the location and
configuration of Hibernate SessionFactory instances, JPA EntityManagerFactory instances,
JDBC DataSource instances, and other related resources. This makes these values easy to
manage and change. Spring offers efficient, easy, and safe handling of persistence resources.
For example, related code that uses Hibernate generally needs to use the same Hibernate
Session to ensure efficiency and proper transaction handling. Spring makes it easy to create
and bind a Session to the current thread transparently, by exposing a current Session
through the Hibernate SessionFactory . Thus, Spring solves many chronic problems of typical
Hibernate usage, for any local or JTA transaction environment.
Integrated transaction management. You can wrap your ORM code with a declarative,
aspect-oriented programming (AOP) style method interceptor either through the
@Transactional annotation or by explicitly configuring the transaction AOP advice in an XML
configuration file. In both cases, transaction semantics and exception handling (rollback and
so on) are handled for you. As discussed in Resource and Transaction Management, you can
also swap various transaction managers, without affecting your ORM-related code. For
example, you can swap between local transactions and JTA, with the same full services (such
as declarative transactions) available in both scenarios. Additionally, JDBC-related code can
fully integrate transactionally with the code you use to do ORM. This is useful for data access
that is not suitable for ORM (such as batch processing and BLOB streaming) but that still
needs to share common transactions with ORM operations.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 124/163
3/10/2020 Data Access
For more comprehensive ORM support, including support for alternative database
technologies such as MongoDB, you might want to check out the Spring Data suite of
projects. If you are a JPA user, the Getting Started Accessing Data with JPA guide from
https://spring.io provides a great introduction.
The major goal of Spring’s ORM integration is clear application layering (with any data access
and transaction technology) and for loose coupling of application objects — no more business
service dependencies on the data access or transaction strategy, no more hard-coded resource
lookups, no more hard-to-replace singletons, no more custom service registries. The goal is to
have one simple and consistent approach to wiring up application objects, keeping them as
reusable and free from container dependencies as possible. All the individual data access
features are usable on their own but integrate nicely with Spring’s application context concept,
providing XML-based configuration and cross-referencing of plain JavaBean instances that need
not be Spring-aware. In a typical Spring application, many important objects are JavaBeans: data
access templates, data access objects, transaction managers, business services that use the
data access objects and transaction managers, web view resolvers, web controllers that use the
business services, and so on.
The infrastructure provides proper resource handling and appropriate conversion of specific API
exceptions to an unchecked infrastructure exception hierarchy. Spring introduces a DAO
exception hierarchy, applicable to any data access strategy. For direct JDBC, the JdbcTemplate
class mentioned in a previous section provides connection handling and proper conversion of
SQLException to the DataAccessException hierarchy, including translation of database-specific
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 125/163
3/10/2020 Data Access
SQL error codes to meaningful exception classes. For ORM technologies, see the next section for
how to get the same exception translation benefits.
When it comes to transaction management, the JdbcTemplate class hooks in to the Spring
transaction support and supports both JTA and JDBC transactions, through respective Spring
transaction managers. For the supported ORM technologies, Spring offers Hibernate and JPA
support through the Hibernate and JPA transaction managers as well as JTA support. For details
on transaction support, see the Transaction Management chapter.
Java Kotlin
JAVA
@Repository
public class ProductDaoImpl implements ProductDao {
XML
<beans>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 126/163
3/10/2020 Data Access
</beans>
The postprocessor automatically looks for all exception translators (implementations of the
PersistenceExceptionTranslator interface) and advises all beans marked with the @Repository
annotation so that the discovered translators can intercept and apply the appropriate
translation on the thrown exceptions.
In summary, you can implement DAOs based on the plain persistence technology’s API and
annotations while still benefiting from Spring-managed transactions, dependency injection, and
transparent exception conversion (if desired) to Spring’s custom exception hierarchies.
4.3. Hibernate
We start with a coverage of Hibernate 5 in a Spring environment, using it to demonstrate the
approach that Spring takes towards integrating OR mappers. This section covers many issues in
detail and shows different variations of DAO implementations and transaction demarcation.
Most of these patterns can be directly translated to all other supported ORM tools. The later
sections in this chapter then cover the other ORM technologies and show brief examples.
As of Spring Framework 5.0, Spring requires Hibernate ORM 4.3 or later for JPA support and
even Hibernate ORM 5.0+ for programming against the native Hibernate Session API. Note
that the Hibernate team does not maintain any versions prior to 5.1 anymore and is likely to
focus on 5.3+ exclusively soon.
The following excerpt from an XML application context definition shows how to set up a JDBC
DataSource and a Hibernate SessionFactory on top of it:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 127/163
3/10/2020 Data Access
XML
<beans>
</beans>
XML
<beans>
<jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/myds"/>
</beans>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 128/163
3/10/2020 Data Access
As of Spring Framework 5.1, such a native Hibernate setup can also expose a JPA
EntityManagerFactory for standard JPA interaction next to native Hibernate access. See
Native Hibernate Setup for JPA for details.
Java Kotlin
JAVA
public class ProductDaoImpl implements ProductDao {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 129/163
3/10/2020 Data Access
This style is similar to that of the Hibernate reference documentation and examples, except for
holding the SessionFactory in an instance variable. We strongly recommend such an instance-
based setup over the old-school static HibernateUtil class from Hibernate’s CaveatEmptor
sample application. (In general, do not keep any resources in static variables unless absolutely
necessary.)
The preceding DAO example follows the dependency injection pattern. It fits nicely into a Spring
IoC container, as it would if coded against Spring’s HibernateTemplate . You can also set up such a
DAO in plain Java (for example, in unit tests). To do so, instantiate it and call
setSessionFactory(..) with the desired factory reference. As a Spring bean definition, the DAO
would resemble the following:
XML
<beans>
</beans>
The main advantage of this DAO style is that it depends on Hibernate API only. No import of any
Spring class is required. This is appealing from a non-invasiveness perspective and may feel
more natural to Hibernate developers.
However, the DAO throws plain HibernateException (which is unchecked, so it does not have to be
declared or caught), which means that callers can treat exceptions only as being generally fatal
— unless they want to depend on Hibernate’s own exception hierarchy. Catching specific causes
(such as an optimistic locking failure) is not possible without tying the caller to the
implementation strategy. This trade off might be acceptable to applications that are strongly
Hibernate-based, do not need any special exception treatment, or both.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 130/163
3/10/2020 Data Access
In summary, you can implement DAOs based on the plain Hibernate API, while still being able to
participate in Spring-managed transactions.
Before you continue, we are strongly encourage you to read Declarative transaction
management if you have not already done so.
You can annotate the service layer with @Transactional annotations and instruct the Spring
container to find these annotations and provide transactional semantics for these annotated
methods. The following example shows how to do so:
Java Kotlin
JAVA
public class ProductServiceImpl implements ProductService {
@Transactional
public void increasePriceOfAllProductsInCategory(final String category) {
List productsToChange = this.productDao.loadProductsByCategory(category);
// ...
}
@Transactional(readOnly = true)
public List<Product> findAllProducts() {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 131/163
3/10/2020 Data Access
return this.productDao.findAllProducts();
}
}
In the container, you need to set up the PlatformTransactionManager implementation (as a bean)
and a <tx:annotation-driven/> entry, opting into @Transactional processing at runtime. The
following example shows how to do so:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
https://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
https://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="transactionManager"
class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<tx:annotation-driven/>
</beans>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 132/163
3/10/2020 Data Access
You can demarcate transactions in a higher level of the application, on top of lower-level data
access services that span any number of operations. Nor do restrictions exist on the
implementation of the surrounding business service. It needs only a Spring
PlatformTransactionManager . Again, the latter can come from anywhere, but preferably as a bean
reference through a setTransactionManager(..) method. Also, the productDAO should be set by a
setProductDao(..) method. The following pair of snippets show a transaction manager and a
business service definition in a Spring application context and an example for a business
method implementation:
XML
<beans>
</beans>
Java Kotlin
JAVA
public class ProductServiceImpl implements ProductService {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 133/163
3/10/2020 Data Access
this.transactionTemplate.execute(new TransactionCallbackWithoutResult() {
public void doInTransactionWithoutResult(TransactionStatus status) {
List productsToChange = this.productDao.loadProductsByCategory(category);
// do the price increase...
}
});
}
}
Spring’s TransactionInterceptor lets any checked application exception be thrown with the
callback code, while TransactionTemplate is restricted to unchecked exceptions within the
callback. TransactionTemplate triggers a rollback in case of an unchecked application exception
or if the transaction is marked rollback-only by the application (by setting TransactionStatus ).
By default, TransactionInterceptor behaves the same way but allows configurable rollback
policies per method.
For distributed transactions across multiple Hibernate session factories, you can combine
JtaTransactionManager as a transaction strategy with multiple LocalSessionFactoryBean
definitions. Each DAO then gets one specific SessionFactory reference passed into its
corresponding bean property. If all underlying JDBC data sources are transactional container
ones, a business service can demarcate transactions across any number of DAOs and any
number of session factories without special regard, as long as it uses JtaTransactionManager as
the strategy.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 134/163
3/10/2020 Data Access
HibernateTransactionManager can export the Hibernate JDBC Connection to plain JDBC access
code for a specific DataSource . This ability allows for high-level transaction demarcation with
mixed Hibernate and JDBC data access completely without JTA, provided you access only one
database. HibernateTransactionManager automatically exposes the Hibernate transaction as a
JDBC transaction if you have set up the passed-in SessionFactory with a DataSource through the
dataSource property of the LocalSessionFactoryBean class. Alternatively, you can specify
explicitly the DataSource for which the transactions are supposed to be exposed through the
dataSource property of the HibernateTransactionManager class.
Spring’s transaction support is not bound to a container. When configured with any strategy
other than JTA, transaction support also works in a stand-alone or test environment. Especially
in the typical case of single-database transactions, Spring’s single-resource local transaction
support is a lightweight and powerful alternative to JTA. When you use local EJB stateless
session beans to drive transactions, you depend both on an EJB container and on JTA, even if you
access only a single database and use only stateless session beans to provide declarative
transactions through container-managed transactions. Direct use of JTA programmatically also
requires a Java EE environment. JTA does not involve only container dependencies in terms of JTA
itself and of JNDI DataSource instances. For non-Spring, JTA-driven Hibernate transactions, you
have to use the Hibernate JCA connector or extra Hibernate transaction code with the
TransactionManagerLookup configured for proper JVM-level caching.
Spring-driven transactions can work as well with a locally defined Hibernate SessionFactory as
they do with a local JDBC DataSource , provided they access a single database. Thus, you need
only use Spring’s JTA transaction strategy when you have distributed transaction requirements.
A JCA connector requires container-specific deployment steps, and (obviously) JCA support in
the first place. This configuration requires more work than deploying a simple web application
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 135/163
3/10/2020 Data Access
with local resource definitions and Spring-driven transactions. Also, you often need the
Enterprise Edition of your container if you use, for example, WebLogic Express, which does not
provide JCA. A Spring application with local resources and transactions that span one single
database works in any Java EE web container (without JTA, JCA, or EJB), such as Tomcat, Resin, or
even plain Jetty. Additionally, you can easily reuse such a middle tier in desktop applications or
test suites.
All things considered, if you do not use EJBs, stick with local SessionFactory setup and Spring’s
HibernateTransactionManager or JtaTransactionManager . You get all of the benefits, including
proper transactional JVM-level caching and distributed transactions, without the inconvenience
of container deployment. JNDI registration of a Hibernate SessionFactory through the JCA
connector adds value only when used in conjunction with EJBs.
You can resolve this warning by making Hibernate aware of the JTA PlatformTransactionManager
instance, to which it synchronizes (along with Spring). You have two options for doing this:
If, in your application context, you already directly obtain the JTA PlatformTransactionManager
object (presumably from JNDI through JndiObjectFactoryBean or <jee:jndi-lookup> ) and feed
it, for example, to Spring’s JtaTransactionManager , the easiest way is to specify a reference to
the bean that defines this JTA PlatformTransactionManager instance as the value of the
jtaTransactionManager property for LocalSessionFactoryBean. Spring then makes the object
available to Hibernate.
More likely, you do not already have the JTA PlatformTransactionManager instance, because
Spring’s JtaTransactionManager can find it itself. Thus, you need to configure Hibernate to
look up JTA PlatformTransactionManager directly. You do this by configuring an application
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 136/163
3/10/2020 Data Access
The remainder of this section describes the sequence of events that occur with and without
Hibernate’s awareness of the JTA PlatformTransactionManager .
When Hibernate is not configured with any awareness of the JTA PlatformTransactionManager , the
following events occur when a JTA transaction commits:
Among other activities, this synchronization can trigger a callback by Spring to Hibernate,
through Hibernate’s afterTransactionCompletion callback (used to clear the Hibernate cache),
followed by an explicit close() call on the Hibernate session, which causes Hibernate to
attempt to close() the JDBC Connection.
In some environments, this Connection.close() call then triggers the warning or error, as the
application server no longer considers the Connection to be usable, because the transaction
has already been committed.
Spring is aware that Hibernate itself is synchronized to the JTA transaction and behaves
differently than in the previous scenario. Assuming the Hibernate Session needs to be closed
at all, Spring closes it now.
Hibernate is synchronized to the JTA transaction, so the transaction is called back through an
afterCompletion callback by the JTA transaction manager and can properly clear its cache.
4.4. JPA
The Spring JPA, available under the org.springframework.orm.jpa package, offers comprehensive
support for the Java Persistence API in a manner similar to the integration with Hibernate while
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 137/163
3/10/2020 Data Access
Using LocalEntityManagerFactoryBean
Using LocalContainerEntityManagerFactoryBean
Using LocalEntityManagerFactoryBean
You can use this option only in simple deployment environments such as stand-alone
applications and integration tests.
XML
<beans>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="myPersistenceUnit"/>
</bean>
</beans>
This form of JPA deployment is the simplest and the most limited. You cannot refer to an existing
JDBC DataSource bean definition, and no support for global transactions exists. Furthermore,
weaving (byte-code transformation) of persistent classes is provider-specific, often requiring a
specific JVM agent to specified on startup. This option is sufficient only for stand-alone
applications and test environments, for which the JPA specification is designed.
server’s default.
XML
<beans>
<jee:jndi-lookup id="myEmf" jndi-name="persistence/myPersistenceUnit"/>
</beans>
This action assumes standard Java EE bootstrapping. The Java EE server auto-detects
persistence units (in effect, META-INF/persistence.xml files in application jars) and persistence-
unit-ref entries in the Java EE deployment descriptor (for example, web.xml ) and defines
environment naming context locations for those persistence units.
In such a scenario, the entire persistence unit deployment, including the weaving (byte-code
transformation) of persistent classes, is up to the Java EE server. The JDBC DataSource is defined
through a JNDI location in the META-INF/persistence.xml file. EntityManager transactions are
integrated with the server’s JTA subsystem. Spring merely uses the obtained
EntityManagerFactory , passing it on to application objects through dependency injection and
managing transactions for the persistence unit (typically through JtaTransactionManager ).
If you use multiple persistence units in the same application, the bean names of such JNDI-
retrieved persistence units should match the persistence unit names that the application uses
to refer to them (for example, in @PersistenceUnit and @PersistenceContext annotations).
Using LocalContainerEntityManagerFactoryBean
You can use this option for full JPA capabilities in a Spring-based application environment. This
includes web containers such as Tomcat, stand-alone applications, and integration tests with
sophisticated persistence requirements.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 139/163
3/10/2020 Data Access
XML
<beans>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="someDataSource"/>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeav
</property>
</bean>
</beans>
XML
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="myUnit" transaction-type="RESOURCE_LOCAL">
<mapping-file>META-INF/orm.xml</mapping-file>
<exclude-unlisted-classes/>
</persistence-unit>
</persistence>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 140/163
3/10/2020 Data Access
This option may conflict with the built-in JPA capabilities of a Java EE server. In a full Java EE
environment, consider obtaining your EntityManagerFactory from JNDI. Alternatively, specify a
custom persistenceXmlLocation on your LocalContainerEntityManagerFactoryBean definition (for
example, META-INF/my-persistence.xml) and include only a descriptor with that name in your
application jar files. Because the Java EE server looks only for default META-INF/persistence.xml
files, it ignores such custom persistence units and, hence, avoids conflicts with a Spring-driven
JPA setup upfront. (This applies to Resin 3.1, for example.)
The LoadTimeWeaver interface is a Spring-provided class that lets JPA ClassTransformer instances
be plugged in a specific manner, depending on whether the environment is a web container or
application server. Hooking ClassTransformers through an agent is typically not efficient. The
agents work against the entire virtual machine and inspect every class that is loaded, which is
usually undesirable in a production server environment.
See the Spring configuration in the AOP chapter for more insight regarding the LoadTimeWeaver
implementations and their setup, either generic or customized to various platforms (such as
Tomcat, JBoss and WebSphere).
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 141/163
3/10/2020 Data Access
XML
<context:load-time-weaver/>
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
...
</bean>
However, you can, if needed, manually specify a dedicated weaver through the loadTimeWeaver
property, as the following example shows:
XML
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>
</property>
</bean>
No matter how the LTW is configured, by using this technique, JPA applications relying on
instrumentation can run in the target platform (for example, Tomcat) without needing an agent.
This is especially important when the hosting applications rely on different JPA
implementations, because the JPA transformers are applied only at the class-loader level and
are, thus, isolated from each other.
XML
<bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager"
<property name="persistenceXmlLocations">
<list>
<value>org/springframework/orm/jpa/domain/persistence-multi.xml</value>
<value>classpath:/my/package/**/custom-persistence.xml</value>
<value>classpath*:META-INF/persistence.xml</value>
</list>
</property>
<property name="dataSources">
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 142/163
3/10/2020 Data Access
<map>
<entry key="localDataSource" value-ref="local-db"/>
<entry key="remoteDataSource" value-ref="remote-db"/>
</map>
</property>
<!-- if no datasource is specified, use this one -->
<property name="defaultDataSource" ref="remoteDataSource"/>
</bean>
Background Bootstrapping
LocalContainerEntityManagerFactoryBean supports background bootstrapping through the
bootstrapExecutor property, as the following example shows:
XML
<bean id="emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="bootstrapExecutor">
<bean class="org.springframework.core.task.SimpleAsyncTaskExecutor"/>
</property>
</bean>
The actual JPA provider bootstrapping is handed off to the specified executor and then, running
in parallel, to the application bootstrap thread. The exposed EntityManagerFactory proxy can be
injected into other application components and is even able to respond to
EntityManagerFactoryInfo configuration inspection. However, once the actual JPA provider is
being accessed by other components (for example, calling createEntityManager ), those calls
block until the background bootstrapping has completed. In particular, when you use Spring
Data JPA, make sure to set up deferred bootstrapping for its repositories as well.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 143/163
3/10/2020 Data Access
It is possible to write code against the plain JPA without any Spring dependencies, by using an
injected EntityManagerFactory or EntityManager . Spring can understand the @PersistenceUnit
and @PersistenceContext annotations both at the field and the method level if a
PersistenceAnnotationBeanPostProcessor is enabled. The following example shows a plain JPA DAO
implementation that uses the @PersistenceUnit annotation:
Java Kotlin
JAVA
public class ProductDaoImpl implements ProductDao {
@PersistenceUnit
public void setEntityManagerFactory(EntityManagerFactory emf) {
this.emf = emf;
}
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 144/163
3/10/2020 Data Access
The preceding DAO has no dependency on Spring and still fits nicely into a Spring application
context. Moreover, the DAO takes advantage of annotations to require the injection of the default
EntityManagerFactory , as the following example bean definition shows:
XML
<beans>
</beans>
XML
<beans>
</beans>
The main problem with such a DAO is that it always creates a new EntityManager through the
factory. You can avoid this by requesting a transactional EntityManager (also called a “shared
EntityManager” because it is a shared, thread-safe proxy for the actual transactional
EntityManager) to be injected instead of the factory. The following example shows how to do so:
Java Kotlin
JAVA
public class ProductDaoImpl implements ProductDao {
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 145/163
3/10/2020 Data Access
@PersistenceContext
private EntityManager em;
The @PersistenceContext annotation has an optional attribute called type , which defaults to
PersistenceContextType.TRANSACTION . You can use this default to receive a shared EntityManager
proxy. The alternative, PersistenceContextType.EXTENDED , is a completely different affair. This
results in a so-called extended EntityManager , which is not thread-safe and, hence, must not be
used in a concurrently accessed component, such as a Spring-managed singleton bean.
Extended EntityManager instances are only supposed to be used in stateful components that, for
example, reside in a session, with the lifecycle of the EntityManager not tied to a current
transaction but rather being completely up to the application.
On the Java EE platform, they are used for dependency declaration and not for resource
injection.
The injected EntityManager is Spring-managed (aware of the ongoing transaction). Even though
the new DAO implementation uses method-level injection of an EntityManager instead of an
EntityManagerFactory , no change is required in the application context XML, due to annotation
usage.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 146/163
3/10/2020 Data Access
The main advantage of this DAO style is that it depends only on the Java Persistence API. No
import of any Spring class is required. Moreover, as the JPA annotations are understood, the
injections are applied automatically by the Spring container. This is appealing from a non-
invasiveness perspective and can feel more natural to JPA developers.
We strongly encourage you to read Declarative transaction management, if you have not
already done so, to get more detailed coverage of Spring’s declarative transaction support.
The recommended strategy for JPA is local transactions through JPA’s native transaction
support. Spring’s JpaTransactionManager provides many capabilities known from local JDBC
transactions (such as transaction-specific isolation levels and resource-level read-only
optimizations) against any regular JDBC connection pool (no XA requirement).
Spring JPA also lets a configured JpaTransactionManager expose a JPA transaction to JDBC access
code that accesses the same DataSource , provided that the registered JpaDialect supports
retrieval of the underlying JDBC Connection . Spring provides dialects for the EclipseLink and
Hibernate JPA implementations. See the next section for details on the JpaDialect mechanism.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 147/163
3/10/2020 Data Access
This is particularly valuable for special transaction semantics and for advanced translation of
exception. The default implementation ( DefaultJpaDialect ) does not provide any special abilities
and, if the features listed earlier are required, you have to specify the appropriate dialect.
See the JpaDialect and JpaVendorAdapter javadoc for more details of its operations and how
they are used within Spring’s JPA support.
The underlying JDBC connection pools need to be XA-capable and be integrated with your
transaction coordinator. This is usually straightforward in a Java EE environment, exposing a
different kind of DataSource through JNDI. See your application server documentation for
details. Analogously, a standalone transaction coordinator usually comes with special XA-
integrated DataSource implementations. Again, check its documentation.
The JPA EntityManagerFactory setup needs to be configured for JTA. This is provider-specific,
typically through special properties to be specified as jpaProperties on
LocalContainerEntityManagerFactoryBean . In the case of Hibernate, these properties are even
version-specific. See your Hibernate documentation for details.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 148/163
3/10/2020 Data Access
Alternatively, consider obtaining the EntityManagerFactory from your application server itself
(that is, through a JNDI lookup instead of a locally declared
LocalContainerEntityManagerFactoryBean ). A server-provided EntityManagerFactory might
require special definitions in your server configuration (making the deployment less
portable) but is set up for the server’s JTA environment.
Such native Hibernate setup can, therefore, serve as a replacement for a standard JPA
LocalContainerEntityManagerFactoryBean and JpaTransactionManager combination in many
scenarios, allowing for interaction with SessionFactory.getCurrentSession() (and also
HibernateTemplate ) next to @PersistenceContext EntityManager within the same local transaction.
Such a setup also provides stronger Hibernate integration and more configuration flexibility,
because it is not constrained by JPA bootstrap contracts.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 149/163
3/10/2020 Data Access
5.1. Introduction
This chapter, describes Spring’s Object-XML Mapping support. Object-XML Mapping (O-X
mapping for short) is the act of converting an XML document to and from an object. This
conversion process is also known as XML Marshalling, or XML Serialization. This chapter uses
these terms interchangeably.
Within the field of O-X mapping, a marshaller is responsible for serializing an object (graph) to
XML. In similar fashion, an unmarshaller deserializes the XML to an object graph. This XML can
take the form of a DOM document, an input or output stream, or a SAX handler.
Some of the benefits of using Spring for your O/X mapping needs are:
Ease of configuration
Consistent Interfaces
Spring’s O-X mapping operates through two global interfaces: Marshaller and Unmarshaller .
These abstractions let you switch O-X mapping frameworks with relative ease, with little or no
change required on the classes that do the marshalling. This approach has the additional
benefit of making it possible to do XML marshalling with a mix-and-match approach (for
example, some marshalling performed using JAXB and some by XStream) in a non-intrusive
fashion, letting you use the strength of each technology.
Java Kotlin
JAVA
public interface Marshaller {
/**
* Marshal the object graph with the given root into the provided Result.
*/
void marshal(Object graph, Result result) throws XmlMappingException, IOException;
}
The Marshaller interface has one main method, which marshals the given object to a given
javax.xml.transform.Result . The result is a tagging interface that basically represents an XML
output abstraction. Concrete implementations wrap various XML representations, as the
following table indicates:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 151/163
3/10/2020 Data Access
DOMResult org.w3c.dom.Node
SAXResult org.xml.sax.ContentHandler
Although the marshal() method accepts a plain object as its first parameter, most
Marshaller implementations cannot handle arbitrary objects. Instead, an object class
must be mapped in a mapping file, be marked with an annotation, be registered with the
marshaller, or have a common base class. Refer to the later sections in this chapter to
determine how your O-X technology manages this.
Java Kotlin
JAVA
public interface Unmarshaller {
/**
* Unmarshal the given provided Source into an object graph.
*/
Object unmarshal(Source source) throws XmlMappingException, IOException;
}
This interface also has one method, which reads from the given javax.xml.transform.Source (an
XML input abstraction) and returns the object read. As with Result , Source is a tagging
interface that has three concrete implementations. Each wraps a different XML representation,
as the following table indicates:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 152/163
3/10/2020 Data Access
DOMSource org.w3c.dom.Node
Even though there are two separate marshalling interfaces ( Marshaller and Unmarshaller ), all
implementations in Spring-WS implement both in one class. This means that you can wire up
one marshaller class and refer to it both as a marshaller and as an unmarshaller in your
applicationContext.xml .
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 153/163
3/10/2020 Data Access
You can use Spring’s OXM for a wide variety of situations. In the following example, we use it to
marshal the settings of a Spring-managed application as an XML file. In the following example,
we use a simple JavaBean to represent the settings:
Java Kotlin
JAVA
public class Settings {
The application class uses this bean to store its settings. Besides a main method, the class has
two methods: saveSettings() saves the settings bean to a file named settings.xml , and
loadSettings() loads these settings again. The following main() method constructs a Spring
application context and calls these two methods:
Java Kotlin
JAVA
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 154/163
3/10/2020 Data Access
The Application requires both a marshaller and an unmarshaller property to be set. We can do
so by using the following applicationContext.xml :
XML
<beans>
<bean id="application" class="Application">
<property name="marshaller" ref="xstreamMarshaller" />
<property name="unmarshaller" ref="xstreamMarshaller" />
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 155/163
3/10/2020 Data Access
</bean>
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/>
</beans>
This application context uses XStream, but we could have used any of the other marshaller
instances described later in this chapter. Note that, by default, XStream does not require any
further configuration, so the bean definition is rather simple. Also note that the
XStreamMarshaller implements both Marshaller and Unmarshaller , so we can refer to the
xstreamMarshaller bean in both the marshaller and unmarshaller property of the application.
XML
<?xml version="1.0" encoding="UTF-8"?>
<settings foo-enabled="false"/>
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:oxm="http://www.springframework.org/schema/oxm" 1
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/oxm https://www.springframework.org/schema/oxm/spring-ox
2
jaxb2-marshaller
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 156/163
3/10/2020 Data Access
jibx-marshaller
Each tag is explained in its respective marshaller’s section. As an example, though, the
configuration of a JAXB2 marshaller might resemble the following:
XML
<oxm:jaxb2-marshaller id="marshaller" contextPath="org.springframework.ws.samples.airline.schema
5.5. JAXB
The JAXB binding compiler translates a W3C XML Schema into one or more Java classes, a
jaxb.properties file, and possibly some resource files. JAXB also offers a way to generate a
schema from annotated Java classes.
Spring supports the JAXB 2.0 API as XML marshalling strategies, following the Marshaller and
Unmarshaller interfaces described in Marshaller and Unmarshaller . The corresponding
integration classes reside in the org.springframework.oxm.jaxb package.
XML
<beans>
<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="classesToBeBound">
<list>
<value>org.springframework.oxm.jaxb.Flight</value>
<value>org.springframework.oxm.jaxb.Flights</value>
</list>
</property>
<property name="schema" value="classpath:org/springframework/oxm/schema.xsd"/>
</bean>
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 157/163
3/10/2020 Data Access
...
</beans>
XML
<oxm:jaxb2-marshaller id="marshaller" contextPath="org.springframework.ws.samples.airline.schema
Alternatively, you can provide the list of classes to bind to the marshaller by using the class-to-
be-bound child element:
XML
<oxm:jaxb2-marshaller id="marshaller">
<oxm:class-to-be-bound name="org.springframework.ws.samples.airline.schema.Airport"/>
<oxm:class-to-be-bound name="org.springframework.ws.samples.airline.schema.Flight"/>
...
</oxm:jaxb2-marshaller>
5.6. JiBX
The JiBX framework offers a solution similar to that which Hibernate provides for ORM: A binding
definition defines the rules for how your Java objects are converted to or from XML. After
preparing the binding and compiling the classes, a JiBX binding compiler enhances the class
files and adds code to handle converting instances of the classes from or to XML.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 158/163
3/10/2020 Data Access
For more information on JiBX, see the JiBX web site. The Spring integration classes reside in the
org.springframework.oxm.jibx package.
XML
<beans>
<bean id="jibxFlightsMarshaller" class="org.springframework.oxm.jibx.JibxMarshaller">
<property name="targetClass">org.springframework.oxm.jibx.Flights</property>
</bean>
...
</beans>
A JibxMarshaller is configured for a single class. If you want to marshal multiple classes, you
have to configure multiple JibxMarshaller instances with different targetClass property values.
XML
<oxm:jibx-marshaller id="marshaller" target-class="org.springframework.ws.samples.airline.schema
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 159/163
3/10/2020 Data Access
5.7. XStream
XStream is a simple library to serialize objects to XML and back again. It does not require any
mapping and generates clean XML.
For more information on XStream, see the XStream web site. The Spring integration classes
reside in the org.springframework.oxm.xstream package.
XML
<beans>
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="aliases">
<props>
<prop key="Flight">org.springframework.oxm.xstream.Flight</prop>
</props>
</property>
</bean>
...
</beans>
By default, XStream lets arbitrary classes be unmarshalled, which can lead to unsafe Java
serialization effects. As such, we do not recommend using the XStreamMarshaller to
unmarshal XML from external sources (that is, the Web), as this can result in security
vulnerabilities.
If you choose to use the XStreamMarshaller to unmarshal XML from an external source, set
the supportedClasses property on the XStreamMarshaller , as the following example shows:
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 160/163
3/10/2020 Data Access
XML
<bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
<property name="supportedClasses" value="org.springframework.oxm.xstream.Flight"/>
...
</bean>
Doing so ensures that only the registered classes are eligible for unmarshalling.
Additionally, you can register custom converters to make sure that only your supported
classes can be unmarshalled. You might want to add a CatchAllConverter as the last
converter in the list, in addition to converters that explicitly support the domain classes
that should be supported. As a result, default XStream converters with lower priorities and
possible security vulnerabilities do not get invoked.
Note that XStream is an XML serialization library, not a data binding library. Therefore, it
has limited namespace support. As a result, it is rather unsuitable for usage within Web
services.
6. Appendix
The tx Schema
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 161/163
3/10/2020 Data Access
We strongly encourage you to look at the 'spring-tx.xsd' file that ships with the Spring
distribution. This file contains the XML Schema for Spring’s transaction configuration and
covers all of the various elements in the tx namespace, including attribute defaults and
similar information. This file is documented inline, and, thus, the information is not
repeated here in the interests of adhering to the DRY (Don’t Repeat Yourself) principle.
In the interest of completeness, to use the elements in the tx schema, you need to have the
following preamble at the top of your Spring XML configuration file. The text in the following
snippet references the correct schema so that the tags in the tx namespace are available to
you:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 1
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans
http://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/sprin
http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spr
</beans>
Often, when you use the elements in the tx namespace, you are also using the elements
from the aop namespace (since the declarative transaction support in Spring is
implemented by using AOP). The preceding XML snippet contains the relevant lines needed
to reference the aop schema so that the elements in the aop namespace are available to
you.
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 162/163
3/10/2020 Data Access
To use the elements in the jdbc schema, you need to have the following preamble at the top of
your Spring XML configuration file. The text in the following snippet references the correct
schema so that the elements in the jdbc namespace are available to you:
XML
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" 1
xsi:schemaLocation="
http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans
http://www.springframework.org/schema/jdbc https://www.springframework.org/schema/jdbc/s
</beans>
Version 5.2.4.RELEASE
Last updated 2020-02-25 16:33:34 UTC
https://docs.spring.io/spring/docs/current/spring-framework-reference/data-access.html#spring-data-tier 163/163