Spring data-completely unified API?

Source: Internet
Author: User
Tags mongodb server neo4j

As one of springsource's parent projects, data is designed to unify and simplify persistent storage for all types of data, instead of sticking to relational databases or nosql data storage.

No matter which type of persistent storage, data access objects (or Dao, that is, data access objects) usually provide CRUD (create, read, update, and delete) for a single domain object) operations, query methods, sorting, and paging methods. Spring data provides a unified interface (crudrepository, pagingandsortingrepository) based on these layers and the implementation of persistent storage.

You may have encountered a spring model object, such as jdbctemplate, to compile the implementation of the access object. For data access objects based on Spring data, we only need to define and compile interfaces of some query methods (based on different continuous storage, the definition may be slightly different ). Spring data will generate the correct implementation at runtime. See the following example:

public interface UserRepository extends MongoRepository<User, String> {         @Query("{ fullName: ?0 }")        List<User> findByTheUsersFullName(String fullName);        List<User> findByFullNameLike(String fullName, Sort sort);}...Autowired UserRepository repo;

This article compares two JPA sub-projects, MongoDB and neo4j. JPA is a part of J2EE and defines a series of APIS for operating relational databases and O/R ing. MongoDB is a scalable, high-performance, open-source, document-oriented database. Neo4j is a graphical database and a complete transactional database for storing graphic data.

All sub-projects of spring data support:

  • Template
  • Object and data storage ing
  • Support for data access objects

Other spring data sub-projects, such as spring data redis and spring data Riak, only provide templates because their corresponding data storage only supports unstructured data, it does not apply to object ing and query.

Next, let's take a closer look at templates, Object Data ing, and data access objects.

Template

The main purpose of the spring data template is to allocate resources and handle exceptions.

The resources mentioned here are data storage resources, which are generally accessed through remote TCP/IP connections. The following example shows how to configure a MongoDB template:

<!-- Connection to MongoDB server --><mongo:db-factory host="localhost" port="27017" dbname="test" /> <!-- MongoDB Template --><bean id="mongoTemplate"class="org.springframework.data.mongodb.core.MongoTemplate">  <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/> </bean>

First, we need to define the connection factory. The connector template will reference this connection factory. In this example, spring data uses the underlying database driver, MongoDB Java driver.

Generally, such underlying database drivers have their own exception handling policies. Spring uses unchecked exceptions. Therefore, developers can decide whether to capture exceptions. The implementation of the MongoDB template is to encapsulate the caught underlying exceptions into non-checked exceptions, which are subclasses of dataaccessexception in spring.

Templates provide data storage-based operations, such as saving, updating, deleting a single record or performing queries. However, all these methods can only be used for the corresponding underlying data storage.

Since the implementation of JPA is already at the abstract layer of the jdbc api layer, spring data JPA does not provide templates. Corresponding to the template concept is the JPA entitymanager, while exception handling is the responsibility of the data access object.

Object and data ing

JPA introduces the O/R ing standard (such as the ing between tables and objects in relational databases ). Hibernate is probably the most widely used JPA standard implementation.

Spring data extends o/R ing support to nosql databases by using class objects. However, in various nosql databases, the data structure is quite different, so it is difficult to form a common API. Each data storage has its own set of annotations to mark the metadata required for ing. Here is a simple example of how to map a simple domain object:

JPA MongoDB Neo4j
@ Entity
@ Table (name = "tusr ")
Public class user {
@ ID
Private string ID;
@ Column (name = "FN ")
Private string name;
Private date lastlogin;
...
}
@ Document (Collection = "USR ")
Public class user {
@ ID
Private string ID;
@ Field ("FN ")
Private string name;
Private date lastlogin;
..
}
@ Nodeentity
Public class user {
@ Graphid
Long ID;
Private string name;
Private date lastlogin;
...
}

If you are familiar with JPA entities, it is easy to see that standard JPA annotations are used here. Spring data reuses these standard annotations without introducing any new content. Object ing is completed by the implementation of these JPA. Mangodb and neo4j require a set of similar annotations. In the above example, we use the class-level annotation collection and nodetype. in mangodb, collection is equivalent to relational database tables, while node and edge are the main data types of graph databases (such as neo4j.

Each JPA object must have a unique identifier, even for MongoDB documents and neo4j nodes.

MongoDB uses the annotation @ ID as the unique identifier (this @ ID is in the org. springframework. Data. annotation package, which is different from the @ ID of JPA ). Neo4j uses the annotation @ graphid. These attribute values are set after the domain object is successfully stored. When the class attribute name is different from the attribute name in the MongoDB document, you can use the @ field annotation.

The two mappings also support references to other objects. See the following example:

JPA MongoDB Neo4j
@ Onetoworkflow
Private list <role> roles;
Private list <role> roles; @ Relatedto (type = "has", direction = direction. Outgoing)
Private list <role> roles;

In JPA, @ onetoworkflow is used to identify one-to-many relationships. Data at multiple ends is usually stored in the subtable and obtained through joint queries. MongoDB does not support joint query between documents. By default, referenced objects and primary objects are stored in the same document. Of course, we can also query the data that references other documents through the virtual union of the client. In neo4j, the relationship is called edges, and edge is also a basic data type.

To sum up, the object ing used by MongoDB and neo4j is very similar to the JPA o/R ing we all know. However, there are significant differences between them due to different data structures. However, in any case, the basic concept is to map objects and data structures.

Data Access Object

You must have written such a DaO object, such as crud operations for a single record, crud operations for multiple records, and query methods based on various query conditions.

With the introduction of JPA, although the entitymanager interface already contains crud operations, writing query methods is still a headache. To complete a query, you need to create a name query, set parameters, and execute the query. See the following example:

@Entity@NamedQuery( name="myQuery", query = "SELECT u FROM User u where u.name = :name" )public class User { ...} @Repository public class ClassicUserRepository {    @PersistenceContext EntityManager em;    public List<User> findByName(String Name) {       TypedQuery<User> q = getEntityManger().createNamedQuery("myQuery", User.class);       q.setParameter("name", fullName);      return q.getResultList();   }    ...

Typedquery Can slightly simplify this process, for example:

@Repositorypublic class ClassicUserRepository {    @PersistenceContext EntityManager em;    public List<User> findByName(String name) {      return getEntityManger().createNamedQuery("myQuery", User.class)         .setParameter("name", fullName)         .getResultList();    }    ...

We still need to write a query method like this, assign values to the query, and execute the query. If spring data JPA can be introduced to implement such queries, the encoding can be greatly simplified as follows:

package repositories; public interface UserRepository extends JpaRepository<User, String> {   List<User> findByName(String name); }

In spring data JPA, we no longer need to define @ namedquerys in the JPA object class to implement jpql query. Instead, we can add a comment such as @ query to each method of the data access object. For example:

@Transactional(timeout = 2, propagation = Propagation.REQUIRED)@Query("SELECT u FROM User u WHERE u.name = 'User 3'")List<User> findByGivenQuery();

Spring data MongoDB and spring data neo4j can make the above method also apply to mangodb and neo4j databases. The following example uses the cipher query language to query the neo4j database.

public interface UserRepository extends GraphRepository<User> {  User findByLogin(String login);   @Query("START root=node:User(login = 'root') MATCH root-[:knows]->friends RETURN friends")  List<User> findFriendsOfRoot(); }

Of course, the naming rules for each persistence layer are slightly different. For example, MongoDB supports a query language called geospatial queries. Generally, we can write the query as follows:

public interface LocationRepository extends MongoRepository<Location, String> {        List<Location> findByPositionWithin(Circle c);        List<Location> findByPositionWithin(Box b);        List<Location> findByPositionNear(Point p, Distance d);}

Spring data also provides a common method for paging and sorting, which requires special parameters to be added to the query method.

The advantages of supporting data access objects are:

  • Reduce the compilation of similar code
  • You can define query statements while defining methods, which also makes the document clearer.
  • Another advantage is that the query statement will be compiled and assembled at the same time as the spring context, rather than compiled at the first time, which can greatly reduce syntax errors in code writing.
Summary

This article only briefly introduces these new content of spring data, intended to clarify similarities and differences with normal JPA. The following links help you better understand spring Data projects.

  • Spring data JPA
  • Spring data MongoDB
  • Spring data neo4j

The answer to the question in the title is obviously no. It is impossible to support all generic APIs for persistent storage. The reason is self-evident. The spring Data project aims to provide a general encoding mode.

The Data Access Object abstracts the physical data layer and provides convenience for writing query methods. Through object ing, the conversion between the domain object and the persistent storage is realized, while the template provides access to the underlying storage entity.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.