Introduction to spring data JPA_ Power node Java college sorting

preface

Since the release of JPA with Java EE 5, it has been sought after by major manufacturers and open source communities. Various commercial and open source JPA frameworks have sprung up, providing developers with rich choices. It changes the previous EJB 2 The image of entity bean in X is cumbersome and difficult to use, which fully absorbs the ORM idea that has been relatively mature in the open source community. In addition, it does not depend on EJB container and can exist as an independent persistence layer technology. At present, more mature JPA frameworks mainly include hibernate entitymanager of JBoss, eclipse link donated by Oracle to eclipse community, openjpa of Apache, etc.

Java persistence specification is from EJB 2 X is separated from the previous entity beans. After EJB3, there will be no entity beans, but entity beans will be implemented in JPA. JPA is an object persistence specification proposed by sun. Each Java EE application server independently selects the specific implementation. The designer of JPA is the author of Hibernate framework. Therefore, hibernate is the default implementation of JPA in JBoss server, and Oracle Weblogic uses eclipse link (formerly called TopLink) as the default JPA implementation, IBM's WebSphere and sun's GlassFish use openjpa (an open source project of APACHE) as their default JPA implementation.

The underlying implementation of JPA is some popular open source ORM (object relational mapping) frameworks. Therefore, JPA actually establishes the mapping relationship between Java entity objects and relational databases, and operates the specification of relational databases through the idea of object-oriented programming.

Spring framework support for JPA

The spring framework supports JPA in the following aspects:

Spring data JPA is more concise

The spring data JPA framework is mainly aimed at the only business logic code that spring has not simplified. So far, developers have saved the only work left to implement the business logic of the persistence layer. The only thing to do is to declare the interface of the persistence layer. The rest is left to spring data JPA to help you!

Let's learn about spring data JPA.

1. Download the required package.

You need to download the release package of spring data JPA first (you need to download spring data Commons and spring data JPA at the same time. Commons is the public basic package of spring data), and add the relevant dependent jar files to the classpath.

2. Let the persistence layer interface Dao (with userdao) inherit the repository interface.

The interface uses generics and needs to provide two types: the first is the domain object type processed by the interface, and the second is the primary key type of the domain object. As follows:

Spring data JPA style persistence layer interface:

The implementation class of userdao is not required, and the framework will complete the business logic for us.

3. Enable the function of scanning and automatically creating proxy in spring configuration file.

4. Test code.

5. Summary

There are three steps to develop the persistence layer using spring data JPA:

1. Declare the interface of the persistence layer, which inherits repository. Repository is a marked interface, which does not contain any methods. Of course, if necessary, spring data also provides several repository sub interfaces, which define some common addition, deletion, modification and query, as well as paging related methods.

2. Declare the required business methods in the interface. Spring data will generate implementation code for it according to the given policy.

3. Add a line of declaration in the spring configuration file to let spring create a proxy object for the declared interface. After < JPA: repositories > is configured, when spring initializes the container, it will scan the package directory and its subdirectories specified by the base package, create a proxy object for the interface that inherits the repository or its sub interface, and register the proxy object as a spring bean. The business layer can directly use the object through the features automatically encapsulated by spring.

In addition, < JPA: repository > also provides some attributes and sub tags to facilitate finer grained control. You can use < context: include Filter >, < context: Exclude Filter > inside < JPA: repository > to filter out some interfaces that you don't want to be scanned.

Interface inheritance

Inheriting repository from the persistence layer interface is not the only option. The repository interface is a core interface of spring data. It does not provide any methods. Developers need to declare the required methods in their own defined interfaces. One way equivalent to inheriting repository is to use the @ repositorydefinition annotation on the persistence layer interface and specify domainclass and IdClass attributes for it. The following two methods are completely equivalent:

Examples of two equivalent inheritance interface modes:

1. If there are many persistence layer interfaces, and each interface needs to declare similar addition, deletion, modification and query methods, it is somewhat cumbersome to directly inherit the repository. It will automatically create addition, deletion, modification and query methods for domain objects for direct use by the business layer. Developers just wrote four more letters of "crud", and immediately provided ten methods for adding, deleting, modifying and querying domain objects out of the box.

2. Using crudrepository also has side effects. It may expose methods you don't want to expose to the business layer. For example, for some interfaces, you only want to provide adding operations rather than deleting methods. In this case, developers can only return to the repository interface, and then copy the method declaration they want to keep to the custom interface in crudrepository

3. Paging query and sorting are common functions of the persistence layer. Spring data provides a pagingandsortingreposition interface for this purpose. It inherits from the crudrepository interface and adds two paging related methods on the basis of crudrepository. However, we rarely inherit the custom persistence layer interface directly from pagingandsortingrepository. Instead, on the basis of inheriting repository or crudrepository, we can add a pageable or sort type parameter at the end of the method parameter list declared by ourselves to specify paging or sorting information, This provides greater flexibility than using pagingandsorting repository directly.

4. Jparepository is an interface for JPA technology inherited from pagingandsortingreposition. Based on the parent interface, it provides other methods, such as flush(), saveandflush(), deleteinbatch(). If there is such a requirement, you can inherit the interface.

Query mode

1. Create a query by resolving the method name

When parsing the method name, the framework will first intercept the redundant prefix of the method name, such as find, findby, read, readby, get and getby, and then parse the rest. And if the last parameter of the method is of type sort or pageable, relevant information will also be extracted for sorting or paging query according to rules.

When querying, you usually need to query according to multiple attributes at the same time, and the query conditions are in various formats (greater than a certain value, in a certain range, etc.). Spring data JPA provides some keywords to express conditional query, which are roughly as follows:

2. Create a query using @ query

@The use of query annotation is very simple. You only need to mark the annotation on the declared method and provide a JP QL query statement, as shown below:

Many developers prefer to use named parameters instead of location numbers when creating jpql, @ query also supports this. In the JP QL statement, the parameters are specified in the format of ": variable". At the same time, use @ param in front of the method parameters to correspond the method parameters to the named parameters in JP QL. An example is as follows:

In addition, developers can also use @ query to perform an update operation. Therefore, we need to use @ modifying to identify the operation as a modify query while using @ query, so that the framework will eventually generate an update operation instead of a query. As follows:

3. Create a query by calling JPA named query statement

Named query is a function provided by JPA to separate query statements from method body for common use by multiple methods. Spring data JPA also provides good support for named queries. Users only need to follow the JPA specification in orm XML file or use @ namedquery (or @ namednatequery) to define a query statement in the code. The only thing to do is to meet the naming rules of "domainclass. Methodname()" when naming the statement. It is assumed that the following interfaces are defined:

If we want to create a named query for findtop5() and associate it with it, we only need to define a named query statement in an appropriate position and name it "accountinfo. Findtop5". When the framework resolves to this method during the creation of the proxy class, it will first find the named query definition named "accountinfo. Findtop5". If it is not found, it will try to resolve the method name, Create a query based on the method name.

Spring data JPA support for transactions

By default, the methods implemented by spring data JPA use transactions. The method for query type is equivalent to @ transactional (readonly = true); The method of adding, deleting and modifying types is equivalent to @ transactional. It can be seen that except that the query method is set to read-only transaction, other transaction attributes adopt default values.

If necessary, the user can explicitly specify the transaction attribute on the interface method using @ transactional, which overrides the default value provided by spring data JPA. At the same time, developers can also use @ transactional to specify transaction attributes on business layer methods, which is mainly for the case that a business layer method calls persistence layer methods multiple times. The transaction of the persistence layer will decide whether to suspend the transaction of the business layer or join the transaction of the business layer according to the set transaction propagation behavior. For specific usage of @ transactional, please refer to the spring reference documentation.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>