I was going through data access technologies supported by Spring, and I noticed that it mentions multiple options and I am not sure about the difference among them:
As I understand, Spring JDBC provides templates for reducing boilerplate code for accessing a database through plain old way - you write your own SQL queries.
Spring-ORM provides simplified templates for accessing databases through ORM technologies, such as Hibernate, My(i)Batis etc.
Spring-DAO as per Spring's website:
The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way
I am a bit clear about ORM vs JDBC as they are aimed at different ways of accessing the DB. But Spring-DAO is just plain confusing!
Could anyone please clarify what exactly are the differences among these three? Which should be preferred in which scenarios?
Also, there is another project Spring-DATA
also available (http://projects.spring.io/spring-data/) Now, is it kind of a parent project for all data access techs supported by Spring or is it just a new name for Spring-DAO?
As I understand, Spring JDBC provides templates for reducing boilerplate code for accessing a database through plain old way - you write your own SQL queries. Spring-ORM provides simplified templates for accessing databases through ORM technologies, such as Hibernate, My(i)Batis etc.
Spring Data JDBC aims at being conceptually easy. In order to achieve this it does NOT offer caching, lazy loading, write behind or many other features of JPA. This makes Spring Data JDBC a simple, limited, opinionated ORM.
Difference Between Spring JDBC and Spring Data JDBCSpring JDBC is a Model class. Spring Data JDBC is a POJO class. Getter and setters are mandatory. Getter and setters are not mandatory.
The most obvious benefit of JDBC over JPA is that it's simpler to understand. On the other side, if a developer doesn't grasp the internal workings of the JPA framework or database design, they will be unable to write good code.
Here is an introduction to each mentioned technology.
Spring-DAO
Spring-DAO is not a spring module in a strict sense, but rather conventions that should dictate you to write DAO, and to write them well. As such, it does neither provide interfaces nor implementations nor templates to access your data. When writing a DAO, you should annotate them with @Repository
so that exceptions linked to the underlying technology (JDBC, Hibernate, JPA, etc.) are consistently translated into the proper DataAccessException
subclass.
As an example, suppose you're now using Hibernate, and your service layer catches HibernateException
in order to react to it. If you change to JPA, your DAOs interfaces should not change, and the service layer will still compile with blocks that catches HibernateException
, but you will never enter these blocks as your DAOs are now throwing JPA PersistenceException
. By using @Repository
on your DAO, the exceptions linked to the underlying technology are translated to Spring DataAccessException
; your service layer catches these exceptions and if you decide to change the persistence technology, the same Spring DataAccessExceptions
will still be thrown as spring have translated native exceptions.
Note however that this has limited usage for the following reasons:
@Repository
, as the beans will be automatically added by the scan procedure. Further, Spring may add other useful features to the annotation.Spring-JDBC
Spring-JDBC provides the JdbcTemplate class, that removes plumbing code and helps you concentrate on the SQL query and parameters. You just need to configure it with a DataSource
, and you can then write code like this:
int nbRows = jdbcTemplate.queryForObject("select count(1) from person", Integer.class);
Person p = jdbcTemplate.queryForObject("select first, last from person where id=?",
rs -> new Person(rs.getString(1), rs.getString(2)),
134561351656L);
Spring-JDBC also provides a JdbcDaoSupport, that you can extend to develop your DAO. It basically defines 2 properties: a DataSource and a JdbcTemplate that both can be used to implement the DAO methods. It also provides an exceptions translator from SQL exceptions to spring DataAccessExceptions.
If you plan to use plain jdbc, this is the module you will need to use.
Spring-ORM
Spring-ORM is an umbrella module that covers many persistence technologies, namely JPA, JDO, Hibernate and iBatis. For each of these technologies, Spring provides integration classes so that each technology can be used following Spring principles of configuration, and smoothly integrates with Spring transaction management.
For each technology, the configuration basically consists in injecting a DataSource
bean into some kind of SessionFactory
or EntityManagerFactory
etc. bean. For pure JDBC, there's no need for such integration classes (apart from JdbcTemplate), as JDBC only relies on a DataSource.
If you plan to use an ORM like JPA or Hibernate, you will not need spring-jdbc, but only this module.
Spring-Data
Spring-Data is an umbrella project that provides a common API to define how to access data (DAO + annotations) in a more generic way, covering both SQL and NOSQL data sources.
The initial idea is to provide a technology so that the developer writes the interface for a DAO (finder methods) and the entity classes in a technology-agnostic way and, based on configuration only (annotations on DAOs & entities + spring configuration, be it xml- or java-based), decides the implementation technology, be it JPA (SQL) or redis, hadoop, etc. (NOSQL).
If you follow the naming conventions defined by spring for the finder method names, you don't even need to provide the query strings corresponding to finder methods for the most simple cases. For other situations, you have to provide the query string inside annotations on the finder methods.
When the application context is loaded, spring provides proxies for the DAO interfaces, that contain all the boilerplate code related to the data access technology, and invokes the configured queries.
Spring-Data concentrates on non-SQL technologies, but still provides a module for JPA (the only SQL technology).
What's next
Knowing all this, you have now to decide what to pick. The good news here is that you don't need to make a definitive final choice for the technology. This is actually where Spring power resides : as a developer, you concentrate on the business when you write code, and if you do it well, changing the underlying technology is an implementation or configuration detail.
Note : Transaction Management
Spring provides an API for transaction management. If you plan to use spring for the data access, you should also use spring for transaction management, as they integrate together really well. For each data access technology supported by spring, there is a matching transaction manager for local transactions, or you can choose JTA if you need distributed transactions. All of them implement the same API, so that (once again) the technology choice is just a matter a configuration that can be changed without further impact on the business code.
Note : Spring documentation
The links to Spring documentation that you mentioned are rather old. Here is the documentation of the latest release (4.1.6, covering all topics) :
Spring-data is not part of the Spring framework. There is a common module that you should first read to get used to the principles. Documentation can be found here:
Spring DAO(Data Access Object): is an object that provides an abstract interface to JDBC implementation frameworks i.e. Spring DAO is generalized concept to access JDBC and Hibernate, MyBatis, JPA, JDO using it's individual Support classes. And it provides generalized exception hierarchy by defining @Repository
annotation. This annotation defines to Spring container for SQL exception translation from SQLException
to Spring's data access strategy-agnostic DataAccessException
hierarchy.
i.e. Easily switch between persistent frameworks, code without worrying about catching exceptions that are specific to each technology.
Spring JDBC: For plain JDBC we use this module, which is only depends on DataSource
and Template classes like JdbcTemplate
, NamedParameterJdbcTemplate
(wraps JdbcTemplate
) and SimpleJdbcTemplate
for reducing cross cutting concerns.
public class EmployeeDao {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public int saveEmployee(Employee e){
return jdbcTemplate.update(query);
}
public int updateEmployee(Employee e){
return jdbcTemplate.update(query);
}
public int deleteEmployee(Employee e){
return jdbcTemplate.update(query);
}
}
and in Spring XML:
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
Spring JDBC also provides JdbcDaoSupport
, NamedParameterJdbcDaoSupport
, SimpleJdbcDaoSupport
, which are support(i.e. convenient) way to extend and develop our own DAO abstract interface as follows:
public interface EmployeeDao {
public void saveEmployee(Employee emp);
}
public class EmployeeDaoImpl extends JdbcDaoSupport implements EmployeeDao{
@Override
public void saveEmployee(Employee emp) {
Object[] inputs = new Object[] {emp.getName(), emp.getSalary(), emp.getDept()};
getJdbcTemplate().update(query, inputs);
}
}
and in spring XML:
<bean id="employeeDAO" class="EmployeeDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
Spring ORM: For ORM tools support such as Hibernate, JPA, MyBatis...easily integrates Spring by injecting DataSource
along with following classes and respective DaoSupport
classes.
SessionFactory
for HibernateEntityManagerFactory
for JPA,SqlSessionFactory
for MyBatisYou create interface like SomeObjectDao
and then create different implementations of this interface like JdbcSomeObjectDao
, HibernateSomeObjectDao
. Then in your SomeObjectService
class you will operate on the SomeObjectDao
interface, and inject there one of the concrete implementations. So each implementation of SomeObjectDao
will hide the details, whether you use JDBC, or ORM etc.
Usually JDBC, and different implementations of ORM throws different kind of exceptions. Spring's DAO support can map those different, technology specific exceptions to common Spring DAO exceptions. So you are decoupled more from the actual implementation. Also Spring's DAO support offers set of abstract *DataSupport
classes which even more help in DAO development. So beside implementing your SomeObjectDao
interface, you can extend one of Spring's *DataSupport
class.
The spring-dao lib stopped in version 2.0.8 (January 2008). The classes in spring-dao were copied to spring-tx. So, if you need a class that you find in spring-dao, add the dependency to spring-tx instead. (Source.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With