Post contents:

1What is the difference between checked and unchecked exceptions?

Checked exceptions are exceptions that are checked at compile time – that fact enforces the developer to either catch it and handle or declare as being thrown and it will be propagated in call stack. Unchecked exceptions are not checked at compile time.

2Why do we (in Spring) prefer unchecked exceptions?

Spring prefers unchecked exception because this way it gives the developer possibility to choose to handle them or not –  he is not enforced to handle them. To use Spring specific exceptions you must use Spring templates. JdbcTemplate takes care of transforming SQLExceptions to meaningful DataAccessExceptions, this is done using SQLExceptionTranslators.

3What is the data access exception hierarchy?

Spring DataAccessExceptions are divided in 4 types:

  1. NonTransientDataAccessException – you must fix the cause of fail and trying will succeed
  2. TransientDataAccessException – no action is required for retry to succeed (timeout etc.)
  3. RecoverableDataAccessException – may succeed if app performs some recovery steps and retries the entire transaction
  4. ScriptException – when initializing a test database using a bean of type DataSourceInitializer fails because of some SQL script error.

4How do you configure a DataSource in Spring? Which bean is very useful for development/test databases?

DataSource is a generalized connection factory. It hides connection pooling and transaction management from application code. Spring obtains connection to the database through a DataSource.

With Spring you can configure different types of DataSources:

  • JDBC-driver defined DataSources
  • JNDI DataSources
  • Connection-pooling DataSources 

JDBC driver-based DataSources are the simples type. Spring has 3 types of them:

  1. DriverManagerDataSource
  2. SimpleDriverDataSource
  3. SingleConnectionDataSource

You configure one as follows:

Connection-pooling DataSources are configured the same way but you may pass some parameters related to the connections pool too.

As for JNDI you can use the jee namespace for XML:

or in case you use Java config:

or a more generic way (as this can be used to lookup any type of object from JNDI)… this will return a factory that in its turn will inject DataSources in places it is required:

A very important DataSource implementation for development/testing purposes is the embedded data source. It runs as part of application instead of being a standalone element. In XML we use jdbc namespace for configuring an in-memory (embedded) database. You specify the SQL DDL (Data Definition Language) and DML (Data Manipulation Language) scripts while declaring the embedded data source.

jdbc:embedded-database does 2 things: adds an embedded database and exposes a DataSource (whose name is specified using the id attribute).

You can do the same using Java:

5What is the Template design pattern and what is the JDBC template?

Although I presume that this question wants to say that JdbcTemplate uses “template method” design pattern – I think that is wrong, as the abstract class it extends doesn’t conform to the structure of the abstract class required for the template method design pattern. Template method design pattern is about the following: you have an abstract class that has one final non-abstract method that defines some algorithm and more abstract methods that are to be implemented in the child classes. And when you run the final method (that you get from the abstract class) you get the algorithm defined in the abstract class but the implementation is done in the child non-abstract class. Meanwhile our JdbcAccessor class that is abstract and is the parent class for JdbcTemplate has no such a method that is final and defines some algorithm.

JdbcTemplate is a convenience class that hides a lot of JDBC boilerplate code and allows to:

  • execute SQL queries
  • execute update statement
  • performs stored procedures calls
  • iterates over ResultSets
  • extracts returned parameter values

6What is a callback? What are the three JdbcTemplate callback interfaces described in the notes? What are they used for? (You would not have to remember the interface names in the exam, but you should know what they do if you see them in a code sample).

As Wikipedia states:

callback is any executable code that is passed as an argument to other code, which is expected to call back(execute) the argument at a given time

In our case we have some interfaces (callback interfaces) that you build some anonymous classes on and pass those classes to methods of JdbcTemplate. 

JdbcTemplate 3 central callback interfaces:

  • RowCallbackHandler – An interface used by JdbcTemplate for processing rows of a ResultSet on a per-row basis
  • CallableStatementCreator – One of the three central callback interfaces used by the JdbcTemplate class. This interface creates a CallableStatement given a connection, provided by the JdbcTemplate class.
  • PreparedStatementCreator – One of the two central callback interfaces used by the JdbcTemplate class. This interface creates a PreparedStatement given a connection, provided by the JdbcTemplate class.


  • ResultSetExtractor
  • BatchPreparedStatementSetter – Batch update callback interface used by the JdbcTemplate class. This interface sets values on a PreparedStatement provided by the JdbcTemplate class
  • ParameterizedPreparedStatementSetter – Parameterized callback interface used by the JdbcTemplate class for batch updates. This interface sets values on a PreparedStatement provided by the JdbcTemplate class.
  • PreparedStatementCallback – Generic callback interface for code that operates on a PreparedStatement
  • StatementCallback – Generic callback interface for code that operates on a JDBC Statement
  • CallableStatementCallback – Generic callback interface for code that operates on a CallableStatement
  • ResultSetExtractor – Callback interface used by JdbcTemplate’s query methods.
  • PreparedStatementSetter – General callback interface used by the JdbcTemplate class. This interface sets values on a PreparedStatement provided by the JdbcTemplate class.

7Can you execute a plain SQL statement with the JDBC template?

Yes, using execute() methods – one of them accepts StatementCallback objects and the other wraps the String you pass in a StatementCallback. StatementCallback in its turn has a doInStatement() method that accepts Statement objects. So you can pass either an anonymous class with overridden doInStatement() method or just a simple String that execute() method of Statement will be run on.

Here’s a rather ugly example:

8Does the JDBC template acquire (and release) a connection for every method called or once per template?

Yes. Connection in acquired by:

and released by:


9Is the JDBC template able to participate in an existing transaction?

If you define a method as @Transactional and internally add some JdbcTemplate code it will run in that transaction; but JdbcTemplate itself cannot manage transactions – that is job of TransactionTemplate.

10What is a transaction? What is the difference between a local and a global transaction?

Transaction is an indivisible unit of work. 

Transactions are described in terms of ACID properties, which are as follows:

  • Atomic: all changes to the database made in a transaction are rolled back if any change fails.
  • Consistent: the effects of a transaction take the database from one consistent state to another consistent state.
  • Isolated: the intermediate steps in a transaction are not visible to other users of the database.
  • Durable: when a transaction is completed (committed or rolled back), its effects persist in the database.

In short a local transaction is a simple transaction that is about one single database; whilst a global one is application server managed and spreads across many components/ technologies. For global transactions consider the case that a record must be persisted in a database ONLY if some message is sent to a queue and processed – if the later fail the transaction must be rolled back.

11Is a transaction a cross cutting concern? How is it implemented in Spring?

Yes as it can affect many components. The core concept in Spring transactions world is the transaction strategy that is defined by PlatformTransactionManager. This interface is a service provider interface. It has multiple implementations and the one you choose depends on your requirements. From PlatformTransactionManager through getTransaction() method – by passing the TransactionDefinition in, you get the TransactionStatus that may represent a new or an existing transaction.

TransactionStatus specifies:

  • isolation
  • propagation
  • propagation 
  • read-only status 

of the transaction to be looked up in the PlatformTransactionManager.

12How are you going to set up a transaction in Spring?

You can define transactions in 2 ways:

  1. Declarative way 
  2. Programmatic way

Declarative way deals with adding some AOP related to transactions to the methods annotated with @Transactional or that have some tx-advices defined by XML.

Programmatic way is about using either TransactionTemplate or directly PlatformTransactionManager.

13What does @Transactional do? What is the PlatformTransactionManager?

Rather than using XML AOP for matching the methods that should be transactional you can add this (@Transactional) annotation. PlatformTransactionManager is an interface that defines the transaction strategy through different implementations that match requirements specific to the project they are used in.

14What is the TransactionTemplate? Why would you use it?

TransactionTemplate is a class that uses callback methods for executing some operations in a transaction. That is achieved by anonymous classes build on TransactionCallback callback interface. 

You may choose to use TransactionTemplate in case you have a small number of transactional methods in your project. 

15What is a transaction isolation level? How many do we have and how are they ordered?

Transaction isolation level is the level of one isolation of one transaction from another. Transaction level is defined from perspective of 3 characteristics:

  1. Dirty reads – one transaction can read uncommitted data from other transaction
  2. Non-repeatable read – occurs when a second transactions reads the same row from first transaction at different times getting different data each time because of first transaction committing some changes or deleting the row.
  3. Phantom reads – occurs when the same search criteria is returning different data because of some other transaction interfering and deleting/adding data.

In Spring we have the following isolation levels:

  • int ISOLATION_DEFAULT = -1 – Use the default isolation level of the underlying datastore.
  • int ISOLATION_READ_UNCOMMITTED = 1 – Indicates that dirty reads, non-repeatable reads and phantom reads can occur.
  • int ISOLATION_READ_COMMITTED = 2 – Indicates that dirty reads are prevented; non-repeatable reads and phantom reads can occur.
  • int ISOLATION_REPEATABLE_READ = 4 – Indicates that dirty reads and non-repeatable reads are prevented; phantom reads can occur.
  • int ISOLATION_SERIALIZABLE = 8 – Indicates that dirty reads, non-repeatable reads and phantom reads are prevented.

16What is the difference between @EnableTransactionManagement and <tx:annotation-driven>?(this is a question from Core Spring 4.2-4.3 Certification Study Guide

<tx:annotation-driven/> is hard-wired to look for a bean called transactionManager while @EnableTransactionManagement will look for PlatformTransactionManager by type – any bean name will be ok.

17How does the JdbcTemplate support generic queries? How does it return objects and lists/maps of objects?

JdbcTemplate supports querying for any type of object assuming you supplied a RowMapper interface implementation defining the way database table should be mapped to some entity type.

It has many overloaded methods for querying the database but mainly you can divide them in:

  1. query()
  2. queryForObject() – if you are expecting only one object
  3. queryForMap() – will return a map containing each column value as key(column name)/value(value itself) pairs.
  4. queryForList() – a list of above if you’re expecting more results 

18What does transaction propagation mean?

Transaction propagation defines whether current transaction will be extended or not.

There is an Enum that specifies the list of all possible propagation types – org.springframework.transaction.annotation.Propagation:

REQUIRES_NEW  create a new transaction, suspend any existing one
MANDATORY use current transaction, throw exception if none exists
REQUIRED use current transaction, if non exists – create one
SUPPORTS use current transaction, execute non-transactionally if none exists
NEVER execute non-transactionally, throw exception if any transaction exists
NOT_SUPPORTED execute non-transactionally, suspend any existing transaction
NESTED if a transaction exists create a nested one in it and execute everything there, else behave like Propagation.REQUIRED


19What happens if one @Transactional annotated method is calling another @Transactional annotated method on the same object instance?

Since transaction-management is implemented using AOP @Transactional annotation will have no effect on the method being called as no proxy is created. The same behavior is characteristic for AOP aspects.

20Where can the @Transactional annotation be used? What is a typical usage if you put it at class level?

If we check the API we can see the following:

If you put @Transactional at class-level this is equal to annotating each method of that class.

21What does declarative transaction management mean?

Declarative transaction management is a model build on AOP. Spring has some transactional aspects that may be used to advise methods for them to work in a transactional manner.

22What is the default rollback policy? How can you override it?

Any RuntimeException (unchecked exception) or Error will cause by default a rollback. Checked exceptions don’t cause a rollback. You can specify 2 different attributes for tx:method in cause you want to rollback or to not rollback for certain exception (no matter it is checked or unchecked):

  1. rollback-for
  2. no-rollback-for

That was for the declarative way. In case you want to set current transaction as “rollback only” you can do that programmatically too:

@Transactional too has some parameters for changing the default behaviour:

  • rollbackFor
  • noRollbackFor
  • rollbackForClassName
  • noRollbackForClassName

23What is the default rollback policy in a JUnit test, when you use the SpringJUnit4ClassRunner and annotate your @Test annotated method with @Transactional?

Test transactions will be automatically rolled back after completion of the test.

24Why is the term “unit of work” so important and why does JDBC AutoCommit violate this pattern?

JDBC AutoCommit will treat each individual SQL statement as a transaction. This means that if logically or from business point of view you need to make sure some statement is ok before executing another one, it would fail. Transactions are meant to solve this problem by “grouping” operations in some logical way so that you confirm to ACID principle (Atomicity, Consistency, Isolation, Durability). 

25What does JPA mean – what is ORM? What is the idea behind an ORM?

JPA stands for Java Persistence API. ORM – Object Relational Mapping. The idea behind ORM is that in applications we deal with objects and classes whilst in databases we have to do with tables and rows. ORM is meant to help us map our entities to the database tables.

26What is a PersistenceContext and what is an EntityManager. What is the relationship between both?

PersistenceContext is a set of entity instances that correspond to persistent entity identity. All the manipulations with the persistent instances are made using EntityManager. EntityManager writes, deletes and searches entities to database.

27Why do you need the @Entity annotation. Where can it be placed?

@Entity annotation is used to mark a class as an entity class that will be mapped to the database using ORM.

28What do you need to do in Spring if you would like to work with JPA?

Because JPA has 2 types of entity managers Spring also has functionality to work with those 2 types.

Here I am talking about:

  1. Application-managed entity managers (produced by LocalEntityManagerFactoryBean of Spring)
  2. Container-managed entity managers (produced by LocalContainerEntityManagerFactoryBean)

It is preferably to use the container-managed type because in this case you will not need the persistence.xml file (located in META-INF) and also it allows for scanning packages for @Entity-annotated classes (using setPackagesToScan() of LocalContainerEntityManagerFactoryBean). 

For the container-managed entity managers there may be an additional source – JNDI. you can get such entity managers in 2 ways:

  1. XML:
  2. Java:

Important to mention:
Although the Java method doesn’t return an EntityManagerFactory, JndiObjectFactoryBean does. 

29Are you able to participate in a given transaction in Spring while working with JPA?

Excerpt from Spring documentation:

Spring JPA also allows a configured JpaTransactionManager to 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. Out of the box, Spring provides dialects for the EclipseLink, Hibernate and OpenJPA JPA implementations. See the next section for details on the JpaDialect mechanism.

Please check 

30What is the PlatformTransactionManager?

PlatformTransactionManager is the central piece in Spring transactions management.

PlatformTransactionManager returns a TransactionStatus when you pass a TransactionDefinition to its getTransaction() method.  In TransactionDefinition that is passed we can specify different transaction characteristics like isolation, propagation and timeout.

31What does @PersistenceContext do?

@PersistenceContext expresses a dependency on a container-managed Entity Manager and its associated persistence context. It does NOT inject an EntityManager – it makes a proxy to the required EntityManager for taking care of correct transaction management and thread-safety.

32What are disadvantages or ORM? What are the benefits?

Benefits Disadvantages
Easy mapping object model to data model Overhead for simple applications
Much less code Need to learn implementation
Concurrency support Performance lower
Automatic management of:

  • Cache
  • Connection pool
  • Transactions
  • Keys
Hard to make complex queries


33What is an “instant repository”? (hint: recall Spring Data)

An instant repository is a repository resulting from extending some class representing an implementation of Repository interface (for example JpaRepository) or annotating some class with @RepositoryDefinition. 

34How do you define an “instant” repository?

You have 2 options:

  1. Extend some implementation of Repository interface.
  2. Annotate the future instant repository class with @RepositoryDefinition

35What is @Query used for?

Spring @Query annotation is used for customize methods of some instant repository.



Please enter your comment!
Please enter your name here