Spring jpa< Transfer >

Source: Internet
Author: User
Tags naming convention jboss jboss server

Objective

Since the release of JPA with Java EE 5, it has been sought after by major vendors and open source communities, and various commercial and open source JPA frameworks have sprung up to provide developers with a wealth of choices. It changed the cumbersome and hard-to-use image of the entity Bean in EJB 2.x, fully absorbing the already relatively mature ORM idea in the open source community. In addition, it does not depend on the EJB container and can exist as a stand-alone persistence layer technology. The more mature JPA frameworks include Jboss Hibernate Entitymanager, Oracle's donation to the Eclipse community Eclipselink, Apache OpenJPA, and more.

The Java Persistence specification, which is separated from the ejb2.x entity Bean, EJB3 the entity Bean later, and instead puts the entity bean in the JPA implementation. JPA is an object persistence specification that Sun proposes, and each Java EE application Server chooses its own implementation, and the JPA designer is the author of the Hibernate framework, so hibernate is the default implementation of JPA in the JBoss server. Oracle's WebLogic uses Eclipselink (formerly called TopLink) as the default JPA implementation, and IBM's WebSphere and Sun GlassFish use OPENJPA by default (an Apache open source project) As its default JPA implementation.
JPA's underlying implementation is a popular open source ORM (Object-relational mapping) framework, so JPA is actually the Java entity object and relational database to establish a mapping relationship, through object-oriented programming of the idea of manipulating relational database specification.

support for JPA by the Spring framework

The support provided by the Spring framework to JPA is mainly reflected in the following areas:

    • First, it makes the JPA configuration more flexible. The JPA specification requires that the configuration file be named Persistence.xml and exist in the Meta-inf directory under the classpath. This file typically contains all the information needed to initialize the JPA engine. The Localcontainerentitymanagerfactorybean provided by Spring provides a very flexible configuration, and the information in the Persistence.xml can be provided here in the form of attribute injection.

    • Second, Spring implements some of the features that are part of the EJB container environment, such as container injection support for @PersistenceContext, @PersistenceUnit.
    • Third, and the most significant, Spring will entitymanager creation and destruction, transaction management and other code extraction, and by its unified management, developers do not need to care about these, business methods only left the operation of the domain object code, transaction management and Entitymanager creation, The destruction of the code no longer requires the developer's concern.

Spring Data JPA is more concise

The spring data JPA framework, which focuses on the only business logic code that is not simplified to the spring, has been saved by the developer's only remaining implementation of the persistence layer's business logic, and the only thing to do is to declare the interface for the persistence layer, and the rest to spring Data JPA To help you finish!

Here's how to learn about spring Data JPA.

1. Download the required packages.

You need to download spring data JPA's release package (you need to download both spring data Commons and spring data JPA two release packages, Commons is the public base package for spring data), and the dependent JAR file Added to the CLASSPATH.

2. Let the persistent Layer interface Dao (Userdao) inherit the Repository interface .

The interface uses generics, requires two types for it: The first domain object type processed for the interface, and the second is the primary key type for the domain object. As follows:

Spring Data JPA-style persistence layer interface:

Public interface Userdao extends Repository<accountinfo, long> {public     accountinfo save (accountinfo AccountInfo);  }

The framework will complete the business logic for us without the need for a Userdao implementation class.

3. Enable scanning and automatically create proxy functions in the Spring configuration file.

<--need to add a reference to the JPA namespace in the <beans> tab--  <jpa:repositories base-package= "Footmark.springdata.jpa.dao "Entity-manager-factory-ref=" Entitymanagerfactory "  

4. Test the code.

Public interface Userdao extends Repository<accountinfo, long> {public  accountinfo save (accountinfo AccountInfo);  What you need to do is just add the following line to declare public accountinfo Findbyaccountid (Long accountId);  

5. Summary

There are approximately three steps required to use Spring Data JPA for persistence layer development:

1. Declare the interface of the persistence layer, the interface inherits Repository,repository is a labeled interface, it does not contain any methods, of course, if necessary, Spring Data also provides several Repository sub-interfaces, which define some common additions and deletions, and pagination-related methods.

2. Declare the required business methods in the interface. Spring Data generates implementation code for it based on the given policy.

3. Add a one-line declaration to the spring configuration file and let Spring create a proxy object for the declared interface. When <jpa:repositories> is configured, Spring initializes the container to scan the Base-package specified package directory and its subdirectories, creates proxy objects for interfaces that inherit Repository or its subinterfaces, and registers the proxy object as Spring beans allow the business layer to use the object directly through the features of spring Auto-encapsulation.

In addition,,<jpa:repository> provides properties and sub-labels for finer-grained control. You can use <context:include-filter>, <context:exclude-filter> to filter out some of the interfaces that you do not want to be scanned inside <jpa:repository>.

Interface Inheritance

Persistence layer Interface Inheritance Repository is not the only option. The Repository interface is a core interface of Spring Data and does not provide any methods, and developers need to declare the required methods in their own defined interfaces. One way to be equivalent to inheriting Repository is to use @RepositoryDefinition annotations on the persistence layer interface and assign them the DomainClass and Idclass properties. The following two ways are completely equivalent:

Two examples of equivalent inherited interface methods:

Public interface Userdao extends Repository<accountinfo, long> {...}  @RepositoryDefinition (DomainClass = accountinfo.class, Idclass = Long.class)  

1. If the persistent layer interface is more, and each interface needs to declare similar additions and deletions to the method, directly inherit Repository is a bit verbose, you can inherit crudrepository, it will automatically create additions and deletions for the domain objects to change the method for the business layer to use directly. Developers just write "Crud" four letters, immediately for the domain object to provide out-of-the-box 10 ways to add and revise.

2. Using crudrepository also has side effects, and it may expose methods that you do not want to expose to the business layer. For example, some interfaces you only want to provide an increased operation and do not want to provide a method of deletion. In this case, developers can only go back to the Repository interface and then copy the method declaration that they want to keep to the custom interface in Crudrepository.

3. Paging queries and sorting are common features of the persistence layer, and Spring Data provides the Pagingandsortingrepository interface, which inherits from the Crudrepository interface, in Crudrepository A new two-page-related approach has been added. However, we seldom inherit the custom persistence layer interface directly from Pagingandsortingrepository, but on the basis of inheriting Repository or crudrepository, add a A pageable or sort parameter that specifies paging or sorting information, which provides greater flexibility than using pagingandsortingrepository directly.

4.JpaRepository is an interface provided by JPA technology that inherits from Pagingandsortingrepository, and it provides other methods, such as flush (), Saveandflush (), on the basis of the parent interface, Deleteinbatch () and so on. If there is such a requirement, you can inherit the interface.

Query Method

1. Create a query by parsing the method name

When parsing a method name, the framework first intercepts the extra prefix of the method name, such as Find, FindBy, read, Readby, get, Getby, and then parses the rest. And if the last parameter of the method is a sort or pageable type, the relevant information is also extracted for sorting by the rules or paging the query.

When creating a query, we express it by using the property name in the method name, such as Findbyuseraddresszip (). When parsing the method, the framework first rejects the findBy, then parses the rest of the attributes, with detailed rules as follows (this assumes that the method is for the domain object AccountInfo type):

    • First Judge Useraddresszip (according to the POJO specification, the first letter to lowercase, the same as the same) is a property of AccountInfo, if so, the query based on the property, if not, continue the second step;
    • A string that starts with the first capital letter from right to left (ZIP), and then checks whether the remaining string is a property of AccountInfo, or, if it is, a query based on that property, and if not, repeats the second step, continuing from right to left, and finally assuming that the user is A property of the AccountInfo;
    • Then processing the remainder (addresszip), first determine whether the user's corresponding type has a addresszip attribute, if any, then the method is ultimately based on "AccountInfo.user.addressZip" the value of the query; otherwise continue to follow the steps The 2 rule is truncated from right to left, and ultimately indicates a query based on the value of "AccountInfo.user.address.zip".

When querying, it is often necessary to query on multiple properties at once, and the conditions of the query are various (greater than a certain value, in a range, etc.), and Spring Data JPA provides some keywords for expressing the criteria query, roughly as follows:

  • and---are equivalent to the AND keyword in SQL, such as Findbyusernameandpassword (String user, Striang pwd);
  • The or---is equivalent to the OR keyword in SQL, such as findbyusernameoraddress (string user, String addr);
  • The between---is equivalent to the between keyword in SQL, such as Findbysalarybetween (int max, int min);
  • The LessThan---is equivalent to "<" in SQL, such as Findbysalarylessthan (int max);
  • GreaterThan---is equivalent to ">" in SQL, such as Findbysalarygreaterthan (int min);
  • IsNull---is equivalent to "is null" in SQL, such as Findbyusernameisnull ();
  • Isnotnull---is equivalent to "is not NULL" in SQL, such as Findbyusernameisnotnull ();
  • Notnull---and isnotnull equivalence;
  • The like---is equivalent to the "as" in SQL, such as Findbyusernamelike (String user);
  • The notlike---is equivalent to "not like" in SQL, such as Findbyusernamenotlike (String user);
  • The order-by---is equivalent to the "FINDBYUSERNAMEORDERBYSALARYASC" in SQL, such as the String user;
  • The not---is equivalent to "in SQL"! = ", such as Findbyusernamenot (String user);
  • In---is equivalent to ' in ' in SQL, such as Findbyusernamein (Collection<string> userlist), the parameter of the method can be either a Collection type or an array or an indefinite length parameter;
  • The notin---is equivalent to "not in" SQL, such as Findbyusernamenotin (Collection<string> userlist), which can be either a Collection type or an array or not Fixed length parameters;

2. Create a query using @Query

The use of @Query annotations is simple, just annotate the annotation on the declared method, and provide a JP QL query statement as follows:

Public interface Userdao extends Repository<accountinfo, long> {  @Query ("Select a from AccountInfo a where A.ACC Ountid =? 1 ") Public  accountinfo Findbyaccountid (Long accountId);     @Query ("Select a from AccountInfo a where a.balance > 1") Public  page<accountinfo> Findbybalancegreaterthan (  Integer balance,pageable pageable);  

Many developers prefer to use named parameters instead of location numbers when creating JP QL, @Query also support this. In the JP QL statement, the parameter is specified in the format ": variable", and the method parameter corresponds to the named parameter in JP QL by using @Param in front of the parameter of the method, as shown in the following example:

Public interface Userdao extends Repository<accountinfo, long> {public  accountinfo save (accountinfo AccountInfo);  @Query ("From AccountInfo a WHERE A.accountid =: id") Public  AccountInfo Findbyaccountid (@Param ("id") Long accountId) ;    @Query ("From AccountInfo a where a.balance >: Balance") Public    page<accountinfo> Findbybalancegreaterthan (  @Param ("balance") Integer balance,pageable pageable);  

In addition, developers can use the @Query to perform an update operation, we need to use the @Query while using the @Modifying to identify the action as a modified query, so that the framework will eventually generate an updated operation, not a query. As shown below:

@Modifying  @Query ("Update AccountInfo a set a.salary =? 1 where A.salary <? 2")  

3. Create a query by invoking a JPA named query statement

A named query is a feature that JPA provides to separate query statements from the body of a method for common use by multiple methods. Spring Data JPA also provides good support for named queries. A user simply needs to define a query statement in the Orm.xml file or in code using the @NamedQuery (or @NamedNativeQuery) in accordance with the JPA specification, and the only thing to do is to give the statement a name that satisfies the " The naming convention for Domainclass.methodname () ". Assume that the following interfaces are defined:

Public interface Userdao extends Repository<accountinfo, long> {  ...  Public list<accountinfo> findTop5 ();  

If you want to create a named query for FINDTOP5 () and associate it with it, we only need to define the named query statement in the appropriate location and name it "ACCOUNTINFO.FINDTOP5", and the framework, when it resolves to the method during the creation of the proxy class, first looks for the name " ACCOUNTINFO.FINDTOP5 named query definition, if not found, attempts to parse the method name and create a query based on the method name.

Spring Data JPA support for transactions

By default, Spring Data JPA implements methods that use transactions. For the method of query type, it is equivalent to @Transactional (readonly=true), and adding and deleting the type method is equivalent to @Transactional. As you can see, other transaction properties take the default value, except that the method of the query is set to read-only transactions.

If the user feels the need, you can use the @Transactional explicitly specify the transaction properties on the interface method, which overrides the default values provided by Spring Data JPA. At the same time, developers can use @Transactional to specify transaction properties on the business layer approach, mainly for a business layer method that calls the persistence layer method multiple times. The persistence layer's transactions determine whether to suspend business-level transactions or join business-level transactions based on the transaction propagation behavior set. Refer to Spring's reference documentation for specific @Transactional use.

Spring jpa< Transfer >

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.