跳至主要内容

Spring Data Access overview

This is the first post of my Spring Data Persistence series, all are based on my personal idea about Spring, it is NOT the official guide. If something is described incorrectly, please let me know. Thanks.


Since Spring 1.x, in the core framework, Spring provided a generic DaoSupport API to simplify the data operations, and now a new Spring Data project was born which provides a modern way for data operations.

DaoSupport and Template API

The legacy DaoSupport and Template API tries to simplify data access of DBRMS, it supports Hibernate, Jdbc, iBatis and JDO etc. In the new Spring, JDO support is deprecated and removed, and the third party project MyBatis(the successor of iBatis) hands over the Spring data access support.
Spring provides lots of encapsulation for the Jdbc operations, and tries to free developers from the tedious Jdbc APIs. Till now, Jdbc support is still considered valuable when Jdbc is chosen in your project.
Besides this, Spring provides a abstraction framework for transaction management, which delegates transaction operations to the one which is relied upon in your project, such as Jdbc transaction, JPA transaction, JTA etc. Benefited from AOP support in Spring, Spring provides some simple approaches to declare the transaction boundary.
If you are using Hibernate and JPA, it is better to use the native API which only needs a simple bean registration in Spring configuration.
In the further posts I will introduce the DaoSupport API and Template API.

Spring Data

Thing was changed now days, we are entering a big data era.
Spring Data project tries to provide a more generic abstraction for different datastore, including RDBMS support, such as Jdbc, JPA etc, and NoSQL support, such as MongoDB, Neo4j etc.
The core API is Repository interface(provided in Spring Data Commons sub project), which utilizes AspectJ and Spring AOP framework, and provides effective data query by method name convention. It is the base of all other certain sub projects.
You can consult the Spring Data project page for more details.
I will provide some posts about the JPA and Mongo sub projects.

DAO is dead?

If you search this topic by Google, you will get much discussion and debate in the search results.
DAO(Date Access Object) is a classic J2EE pattern which is very popular in J2EE 1.4, it was described in the famous Core J2EE Patterns book.
In the wikipedia Data Access Object page, DAO is described as below:
In computer software, a data access object (DAO) is an object that provides an abstract interface to some type of database or other persistence mechanism.
In the next sections of this wiki page, JPA, JDO specifications and some products, such as Hibernate, iBatis, Doctrine are considered as DAO implementation.
The world was changed when Java EE 5 was born, and EJB 3 programming is simplified dramatically, most of the classic J2EE patterns are proved they are anti-patterns, we have got POJO programming capability in the newest Java EE 5 and Java EE 6. That means some of the legacy J2EE patterns are out of date and no use.
Adam Bien wrote much blog entries about the newest Java EE patterns, and wrote down two books to refresh the Java EE patterns, including the alternative of DAO.
Obviously, DAO is still needed when you are using Jdbc in projects. But when you are using JPA, the basic CURD operations are included in EntityManager, and fields are mapped to the table columns automatically, we do not need extra effort on them. The left is the custom queries for some purpose, we have to write them ourselves.
Adam Bien introduced a CrudService to resolve this issue, thus we can avoid to repeat the common operations.
In Spring ecosystem, the newest Spring Data umbrella projects fill the blank table.

DataAccessException and the Exception Translator

In the Spring Jdbc support, the most attractive feature is the encapsulation of SQLException.
If you are coding against Jdbc API without Spring, you could be bored by the thrown SQLException with stupid error code and description which are very dependent on the Jdbc driver provider.
Spring redesigns the SQLExcdption processing and tries to categorize the exceptions and translates it into Spring friendly DataAccessException(and its subclasses). The work is done by the SQLExceptionTranslator.
Please explore the DataAccessException class and its sub classes for more details.
Besides, Spring also provides a generic PersistenceExceptionTranslator API to transform the exceptions from other persistence technologies(such as Hibernate, JPA, Mongo etc) to the DataAcessException. For Hibernate and JPA if you have registered a Hibernate specific SessionFactoryBean or a JPA specific EntityFactoryBean in Spring configuration, it also registered a certain PersistenceExceptionTranslator for you. For Mongo, you have to register a MongoExceptionTranslator bean yourself.

Summary

Spring DaoSupport and Template API had been widely used in projects for years. But for new projects, personally, I think the DaoSupport API should be avoided. The JpaDaoSupport is already marked as @Deprecated, and the HibernateDaoSupport also should be deprecated in future, there is no update for years.
You can switch to use native API when you are using Hibernate and JPA. Spring Data is another alternative of data operations. We will discuss them later.

评论

此博客中的热门博文

Create a restful application with AngularJS and Zend 2 framework

Create a restful application with AngularJS and Zend 2 framework This example application uses AngularJS/Bootstrap as frontend and Zend2 Framework as REST API producer. The backend code This backend code reuses the database scheme and codes of the official Zend Tutorial, and REST API support is also from the Zend community. Getting Started with Zend Framework 2 Getting Started with REST and Zend Framework 2 Zend2 provides a   AbstractRestfulController   for RESR API producing. class AlbumController extends AbstractRestfulController { public function getList() { $results = $this->getAlbumTable()->fetchAll(); $data = array(); foreach ($results as $result) { $data[] = $result; } return new JsonModel(array( 'data' => $data) ); } public function get($id) { $album = $this->getAlbumTable()->getAlbum($id); return new JsonModel(array("data" =>

JPA 2.1: Attribute Converter

JPA 2.1: Attribute Converter If you are using Hibernate, and want a customized type is supported in your Entity class, you could have to write a custom Hibernate Type. JPA 2.1 brings a new feature named attribute converter, which can help you convert your custom class type to JPA supported type. Create an Entity Reuse the   Post   entity class as example. @Entity @Table(name="POSTS") public class Post implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="ID") private Long id; @Column(name="TITLE") private String title; @Column(name="BODY") private String body; @Temporal(javax.persistence.TemporalType.DATE) @Column(name="CREATED") private Date created; @Column(name="TAGS") private List<String> tags=new ArrayList<>(); } Create an attribute convert

Auditing with Hibernate Envers

Auditing with Hibernate Envers The approaches provided in JPA lifecyle hook and Spring Data auditing only track the creation and last modification info of an Entity, but all the modification history are not tracked. Hibernate Envers fills the blank table. Since Hibernate 3.5, Envers is part of Hibernate core project. Configuration Configure Hibernate Envers in your project is very simple, just need to add   hibernate-envers   as project dependency. <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-envers</artifactId> </dependency> Done. No need extra Event listeners configuration as the early version. Basic Usage Hibernate Envers provides a simple   @Audited   annotation, you can place it on an Entity class or property of an Entity. @Audited private String description; If   @Audited   annotation is placed on a property, this property can be tracked. @Entity @Audited public class Signup implements Serializa