Spring Data JDBC and JPA
Learn about a few interview questions regarding Spring data JDBC and JPA.
We'll cover the following
- How does Spring provide DAO support?
- Describe Spring DAO support classes.
- What annotation is used to mark DAO in Spring?
- What is Spring data JDBC?
- What tasks are performed by Spring JDBC?
- What is the difference between JDBC and Spring JDBC?
- Name the classes in Spring JDBC API?
- What are the advantages of JdbcTemplate in Spring?
- Why is NamedParameterJdbcTemplate class used?
- How are records from a database fetched when using JdbcTemplate?
- What is the difference between a RowMapper and ResultSetExtractor?
- Explain Spring’s exception handling support with DataAccessException.
- What is SQLExceptionTranslator?
- What are JdbcTemplate callback interfaces?
- What is Spring Data?
- What is JPA?
- What is the difference between JPA and Spring Data JPA?
- What is the difference between CrudRepository and JpaRepository?
- Which No SQL databases does Spring support?
- Which ORMs are supported by Spring?
- What is Hibernate?
- What are the different types of transaction management supported by Spring?
- Which transaction management type is preferred in Spring?
- What are some benefits of using Spring Transactions?
- What happens when the @Transactional annotation is used on a method?
- What is the difference between JdbcTemplate and JPA?
How does Spring provide DAO support?
Spring DAO support makes it easy to work with different data access technologies in a consistent way which makes it easy to switch between technologies like JDBC, Hibernate, or JDO. Main features of Spring DAO support are:
- Exception handling: Technology specific exception like
SQLException
is translated to Spring’sDataAccessException
. Checked exceptions in Hibernate, JPA, and JDO can be converted to runtime exceptions. - Abstract DAO support classes: Spring provides abstract classes for different data access technologies which provide methods for data source and other configuration settings. These include the
JdbcDaoSupport
,HibernateDaoSupport
,JdoDaoSupport
, andJpaDaoSupport
classes.
Describe Spring DAO support classes.
Spring provides technology specific abstract classes for DAO support. These classes have methods for providing data source and other configuration settings specific to the data access technology. Abstract DAO support classes are:
JdbcDaoSupport
class requiresDataSource
and returnsJdbcTemplate
instance.HibernateDaoSupport
class requiresSessionFactory
and returnsHibernateTemplate
instance.JdoDaoSupport
class requiresPersistenceManagerFactory
and returnsJdoTemplate
instance.JpaDaoSupport
class requiresEntityManagerFactory
and returnsJpaTemplate
instance.
What annotation is used to mark DAO in Spring?
The @Repository
annotation is used for DAO classes. This annotation provides the Spring exception translation facility which converts a technology specific expectation to a DataAccessException
.
What is Spring data JDBC?
Spring Data JDBC framework is part of Spring Data. It provides support for JDBC repositories. Spring Data JDBC is a simple but limited ORM. It does not implement features like caching, lazy loading, and write-behind. Unlike Spring Data JPA, it does not provide schema generation and the developer must explicitly create the schema.
Spring JDBC uses methods like update(String sql)
, execute (String sql)
, and query(String sql, ResultSetExtractor rse)
to interact with the database.
What tasks are performed by Spring JDBC?
Spring JDBC is designed to reduce boilerplate code. It performs the following tasks:
- Opens the connection
- Prepares and executes statement
- Iterates over the resultset
- Handles any exceptions that arise
- Manages the transaction
- Closes the connection
What is the difference between JDBC and Spring JDBC?
Spring JDBC removes the need of manual exception handling and transaction management.
Checked exceptions that need to be explicitly written in JDBC are converted to runtime exceptions in Spring JDBC.
Spring JDBC automatically cleans up resources by closing the database connection.
Name the classes in Spring JDBC API?
JdbcTemplate
class is the central class that handles JDBC workflow managing creation of SQL statement and its execution.NamedParameterJdbcTemplate
class provides support for named parameters to replace the ? placeholders in a query.
What are the advantages of JdbcTemplate
in Spring?
The JdbcTemplate
class uses the JDBC API to connect to a database and execute SQL queries. JdbcTemplate
class removes the need to write boilerplate JDBC connection management code. It also removes the need for manual exception handling.`
Why is NamedParameterJdbcTemplate
class used?
The NamedParameterJdbcTemplate
class is used to pass a value to a named parameter. It is better than a prepared statement with question marks. When we use names instead of ? it is better to remember the data in the column.
How are records from a database fetched when using JdbcTemplate
?
The query()
method of the JdbcTemplate
class is used to fetch records from a database. The results are mapped using either the ResultSetExtractor
, or the RowMapper
interface.
What is the difference between a RowMapper
and ResultSetExtractor
?
The RowMapper
is executed for every row. It keeps looping over the result set and makes it available one row at a time. On the other hand, the ResultSetExtractor
fetches all the records at once.
RowMapper
is used when each row maps to a single object, e.g., return a list of players along with their country.
If we need to map multiple rows returned by a query to a single object, ResultSetExtractor
is the appropriate choice, e.g., return a list of countries along with the number of players from that country. ResultSetExtractor
allows manipulation of data as all rows of the result set are available at once.
Explain Spring’s exception handling support with DataAccessException
.
DataAccessException
is a kind of runtime exception. It wraps technology specific exceptions to let the developer handle errors without knowing the details of the data access API which means that it is possible to catch JDBC exceptions in a generic way without knowing that JDBC is being used in the DAO layer. This allows one to change between data access technologies (e.g., JDBC, JPA, Hibernate) without changing a lot of code.
The developer need not write catch blocks for runtime exceptions.
What is SQLExceptionTranslator
?
The SQLExpectionTranslator
interface translates a SQLException
to Spring’s DataAccessException
. The returned exception contains the original SQLException
as the root cause.
What are JdbcTemplate
callback interfaces?
JdbcTemplate
processes a query with the questionmark (?
) placeholder. Spring offers a number of callbacks to execute the query. These are as follows:
PreparedStatement
: operates on a prepared statement and can execute multiple operations on a single prepared statement.ResultSetExtractor
: processes the entire result set at once.RowCallbackHandler
: can perform processing on each row like converting rows to XML, streaming them to a file and filtering rows.RowMapper
: maps a single row of the result set to an object
What is Spring Data?
Spring Data is a Spring project for providing a consistent way of accessing different data stores. It provides support for both relational and no-sql databases. Spring Data contains many modules, with the core modules being spring-data-commons
. Other modules include spring-data-jdbc
, spring-data-redis
, and spring-data-mongo
.
The aim of Spring Data is to bring consistency in the way data is accessed in SQL and NoSQL databases.
What is JPA?
Java Persistence API (JPA) is an interface that defines a mapping between relations and objects. It defines how a Java object is mapped to a database table. JPA provides a mechanism to query the database and provide the results back as a collection of Java objects or provide Java objects to be stored in the database. The underlying ORM implementation converts these API calls to SQL queries.
When using JPA, we can easily change the underlying data access technology e.g., using Oracle in production and H2 during testing.
What is the difference between JPA and Spring Data JPA?
JPA is a specification for accessing a data store for storage and retrieval.
Spring Data JPA is a part of Spring Data project. It is not a JPA implementation. Spring Data JPA uses Hibernate as the default JPA implementation.
Spring Data JPA contains JPA repositories which define query methods. This eliminates the need to write common queries. The name of the method declared in the repository interface is automatically converted into low level SQL queries by Spring.
What is the difference between CrudRepository
and JpaRepository
?
CrudRepository
provides CRUD operations.
JpaRepository
extends the PagingAndSortingRepository
which extends the CrudRepository
.
JpaRepository
provides methods for pagination and sorting of records in addition to CRUD operations.
Which No SQL databases does Spring support?
Spring supports a number of No SQL databases including MongoDB, Cassandra, Redis and HBase.
Which ORMs are supported by Spring?
Hibernate, JDO, Oracle TopLink and OJB are supported by Spring.
What is Hibernate?
Hibernate is by far the most popular JPA implementation. It existed even before JPA came into existence and has a lot more to it than being a JPA implementation. Hibernate makes creating queries under the hood and interacting with databases easy.
What are the different types of transaction management supported by Spring?
Spring provides support for both programmatic and declarative transaction management. Programmatic transaction management offers more flexibility but it is difficult to maintain as it requires controlling transactions through code. The transaction management code is tightly bound with the business logic as the developer is responsible to manually commit or rollback a transaction.
In declarative transaction management, the business logic and transaction management code is separate. Transactions are implemented as a cross-cutting concern or by using the @Transactional
annotation.
Which transaction management type is preferred in Spring?
Declarative transaction management which separates transaction management from the business logic is preferred because it can be implemented as a cross-cutting concern.
What are some benefits of using Spring Transactions?
-
Spring transaction management allows the developer to handle transactions across different data access technologies in a consistent way.
-
Declarative transaction management is implemented using the Spring aspect-oriented programming and does not impact application code.
-
Programmatic transaction management API offered by Spring is simpler as compared to Java Transaction API.
What happens when the @Transactional
annotation is used on a method?
The @Transactional
annotation is used in declarative transaction management and is used to handle transactions. It is based on the AOP concept.
Under the hood, the @Transactional
annotation behaves in the same manner as the transaction advice. Spring creates a proxy around the bean to inject transaction management behavior before, after or around the method calls on the bean.
The @Transactional
annotation supports both local and global transactions. It can only be applied to public methods.
What is the difference between JdbcTemplate and JPA?
In JdbcTemplate, the database schema is not accessed via a domain model. JdbcTemplate allows more flexibility as it works on a lower level, but it also increases boilerplate code.
JPA requires that the database schema is mapped to a domain model. It makes interacting with databases simpler.
Get hands-on with 1400+ tech skills courses.