Learn spring Data JPA in layman's

Source: Internet
Author: User
Tags jboss

Chapter One: Introduction to Spring Data JPA

Spring data is an open-source framework for simplifying database access and supporting cloud services. Its main goal is to make access to data easy and fast, and to support map-reduce framework and cloud computing data Services. Spring Data contains multiple sub-projects: Commons-Provides a shared infrastructure for use by individual sub-projects, supporting cross-database persistence JPA-simplifies the creation of the JPA data access layer and the persistence layer capabilities across storageHadoop-The Spring-based Hadoop job configuration and the MapReduce job of a POJO programming model Key-value-integrates Redis and Riak to provide a simple package document in a number of common scenarios-integrated documentation database : CouchDB and MongoDB and provides basic configuration mapping and database support graph-Integrated neo4j provides a powerful POJO-based programming model graph Roo Addon-roo support for NEO4JJDBC Extensio NS-Support for Oracle RAD, advanced queuing, and advanced data types mapping-Grails-based object mapping framework supporting different database examples-sample programs, documents, and graph databases guidance-advanced documentation Spring Data JPA is What a framework provided by spring for simplifying JPA development nspring data JPA can greatly simplify the JPA notation, enabling access to and manipulation of the information in almost no-write implementations. In addition to CRUD, it also includes some common functions such as paging, sorting, and so on. What spring data JPA has to look at is the interface provided by spring data JPA and is the core concept of spring data JPA: 1:repository: The topmost interface is an empty interface, The purpose is to unify the types of all repository and to automatically identify the components when they are scanned. 2:crudrepository: is a repository sub-interface that provides CRUD functionality 3:pagingandsortingrepository: is a crudrepository sub-interface, Add pagination and Sorting features 4:jparepository: is the Pagingandsortingrepository sub-interface, added some useful functions, such as: batch operation. 5:jpaspecificationexecutor: The interface used to do the query 6:specification: A query specification provided by Spring Data JPA, to make complex queries, simply set the query criteria around this specification toHelloWorldn Environment constructs a common Java project in eclipse, mainly to add a bunch of jar packages. 1: First download Spring data Common and spring data JPA packages to the website, add the Dist jar package to the project, here is Spring-data-commons-1.5.0.release.jar and SPRING-DATA-JPA-1.3.2.RELEASE.JAR2: Add Spring3.2.3 jar package to the project 3:JPA the implementation of the Hibernate4.2.0, a total of additional added to the following Jar:antlr-2.7.7.jar , Aopalliance-1.0.jar, Asm-3.2.jar, Aspectjrt-1.7.1.jar, Aspectjweaver-1.7.1.jar, Commons-beanutils-1.8.3.jar, Commons-codec-1.7.jar, Commons-collections-3.2.1.jar, Commons-dbcp-1.4.jar, Commons-fileupload-1.2.2.jar, Commons-io-2.4.jar, Commons-lang3-3.1.jar, Commons-logging-1.1.1.jar, Commons-pool-1.6.jar, Dom4j-1.6.1.jar, Hibernate-commons-annotations-4.0.1.final.jar, Hibernate-core-4.2.0.final.jar, Hibernate-entitymanager-4.2.0.final.jar, Hibernate-jpa-2.0-api-1.0.1.final.jar, Javassist-3.15.0-GA.jar, Jboss-logging-3.1.0.ga.jar, Jboss-transaction-api_1.1_spec-1.0.0.final.jar, Mysql-connector-java-5.1.9.jar, The Slf4j-api-1.7.3.jarn entity object is the previous implementation @entity@table (Name= "Tbl_user") public class Usermodel {@Idprivate Integer uuid; Private StringName;private Integer age;//Omit Getter/setter}ndao interface public interface Userrepository extends Jparepository<usermodel , integer>{//empty, can not write anything} without providing implementations, Spring Data JPA will do everything for us n write a service for the logic layer, in fact, the equivalent of DAO's client, Used to test @service@transactionalpublic class Client {@Autowiredprivate userrepository ur; public void Testadd ( Usermodel um) {ur.save (UM);}  public static void Main (string[] args) {ApplicationContext ctx = new Classpathxmlapplicationcontext (" Applicationcontext.xml ");  client C = (client) Ctx.getbean (" Client "); Usermodel um = new Usermodel (); Um.setage (1); Um.setname ("Zhang San"); Um.setuuid (1);  c.testadd (UM); } Chapter II: Jparepository basic FunctionsBasic function Demonstration of jparepositoryA concrete look at the code shows where: the implementation class of the Pageable interface is the implementation class of the Pagerequest,page interface is Pageimpl. Example below:page<usermodel> p = ur.findall (new Pagerequest (0,2,new Sort (Direction. DESC, "UUID"))); System. out. println ("list=" +p.getcontent ());Chapter III: Query of JparepositoryDirectly in the interface to define the query method, if it is compliant, you can not write the implementation, the currently supported keywords are as follows: Spring Data JPA Framework in the method name resolution, the method name will be a redundant prefix interception, such as Find, FindBy, read, Readby, Get, Getby, and then parse the rest of the section. If you create the following query: Findbyuserdepuuid (), the framework when parsing the method, the first to remove the findBy, and then to parse the remaining attributes, assuming the query entity is DOC1: First Judge Userdepuuid (according to the POJO specification, The first letter to lowercase) is a property of the query entity and, if it is, a query based on that property, and if it does not, proceed to the second step; 2: The string that starts with the first capital letter from right to left is the UUID here), and then checks whether the remaining string is a property of the query entity, and if so, is a query based on the property, and if it does not, repeat the second step, continue from right to left, and finally assume that the user is a property of the query entity; 3: Then the remainder (DEPUUID) is processed to determine if the type of the user has a Depuuid attribute, and if so, This means that the method is ultimately queried according to the value of "Doc.user.depUuid", otherwise it continues to be intercepted from right to left according to the rules of Step 2, and ultimately indicates a query based on the value of "Doc.user.dep.uuid". 4: There may be a special case, such as doc contains a user attribute, there is also a USERDEP property, there is confusion. You can explicitly add "_" between attributes to explicitly express the intent, such as "Findbyuser_depuuid ()" or "Findbyuserdep_uuid ()" Special parameters: You can also add paging or sorting parameters directly to the parameters of the method, such as:page< Usermodel> Findbyname (String name, pageable pageable); List<usermodel> Findbyname (String name, sort sort);  can also use JPA namedqueries, as follows: 1: Use @namedquery on entity classes, The example is as follows: @NamedQuery (name = "Usermodel.findbyage", query = "Select O from Usermodel o where o.age >=? 1") 2:The implemented DAO's repository interface defines a method with the same name, with the following examples: public list<usermodel> findbyage (int age); 3: Then you can use it, Spring will find out if there is a namedquery with the same name, and if so, it will not be parsed according to the method defined by the interface.  using @queryYou can use @Query on a custom query method to specify the query statement that the method executes, such as: @Query ("Select O from Usermodel o where o.uuid=?1") public list<usermodel> Findbyuuidorage (int uuid); Note:1: The number of parameters of the method must be the same as the number of parameters required in @Query 2: If it is like, the following parameters need to be preceded or followed by "%", for example: @Query ("Select O from the Usermodel o where O.name like?" 1 % ") public list<usermodel> findbyuuidorage (String name); @Query ("Select O from Usermodel o where o.name like%?1") public list<usermodel> findbyuuidorage (String name); @Query ("Select O from Usermodel o where o.name like%?1%") public list<usermodel> findbyuuidorage (String name); Of course, it is possible to pass the parameter value when you can not add '% ', of course, plus can not be wrong n also use @Query to specify a local query, as long as set Nativequery to True, such as: @Query (value= "SELECT * from Tbl_user Where name like%?1 ", nativequery=true) public list<usermodel> findbyuuidorage (String name); Note:The current version of the local query does not support page flipping and dynamic sorting using the named parameters, using @param, such as: @Query (value= "Select O from Usermodel o where o.name like%:nn") public list& Lt Usermodel> Findbyuuidorage (@Param ("nn") String name), as well as support for updating the Query statement of the class, add @modifying, for example: @Modifying @query (value= "Update Usermodel o set o.name=:newname where o.name like%:nn") public int findbyuuidorage (@Param ("nn") String name, @Param ("NewName") String newName); Note:1: The return value of the method should be int, indicating the number of rows affected by the UPDATE statement 2: A transaction must be added where the call is made, no transaction is not performed properlyquery function of jparepositoryThe order in which queries are created when spring Data JPA creates a proxy object for an interface, what strategy does it take precedence if it finds that there are a number of these situations available? <jpa:repositories> provides the Query-lookup-strategy property to specify the order of lookups. It has the following three values: 1:create-if-not-found: If the method specifies a query statement through @query, the statement is used to implement the query, and if not, the lookup defines whether a named query that matches the criteria is defined, and if it is found, the named query is used; The query is created by parsing the method name. This is the default value for the Query-lookup-strategy property 2:create: Creates a query by parsing the method name. Even if there is a named query that matches, or if the method passes the specified query statement @Query, the 3:use-declared-query is ignored: If the method specifies a query statement through @query, the statement is used to implement the query; Finds whether a named query that matches the criteria is defined and, if found, uses the named query; If neither is found, throws an exception   fourth: Custom extension jparepository If you don't want to expose so many ways, you can customize your own repository, You can also add your own repository inside the public method of course more flexible is to write an implementation class, to achieve their own Method 1: Write a class with the same name as the interface, plus the suffix impl, which is configured in the previous XML, can be automatically scanned. This class does not need to implement any interfaces. 2: In the interface to add their own methods, such as: Public page<object[]> getbycondition (Userquerymodel u); 3: In the implementation class, to implement this method is good, will be automatically found
    public class Userrepositoryimpl {          @PersistenceContext          private entitymanager em;             Public page<object[]> getbycondition (Userquerymodel u) {      String hql = ' Select O.uuid,o.name from Usermodel o whe Re 1=1 and O.uuid=:uuid ";              Query q = em.createquery (HQL);              Q.setparameter ("UUID", U.getuuid ());                      Q.setfirstresult (0);              Q.setmaxresults (1);           page<object[]> page = new pageimpl<object[]> (Q.getresultlist (), New Pagerequest (0,1), 3);               return page;      }}  
The fifth chapter: Specifications Query Spring Data JPA support JPA2.0 criteria query, the corresponding interface is jpaspecificationexecutor. Criteria query: is a type-safe and more object-oriented query This interface is basically defined around the specification interface, and the specification interface only defines one of the following methods: Predicate Topredicate (Root <T> root, criteriaquery<?> query, Criteriabuilder CB); To understand this approach, and to use it correctly, you need to be familiar with and understand JPA2.0 's criteria query, because the parameters and return values of this method are the objects defined in the JPA standard. Criteria Query Basic ConceptsCriteria queries are based on the concept of a meta-model, which is defined for a managed entity that is a concrete persistence unit, which can be an entity class, an embedded class, or a mapped parent class. Criteriaquery interface: Represents a specific top-level query object that contains various parts of the query, such as SELECT, from, where, group by, order by, and so on Note:The Criteriaquery object only works on the criteria query for an entity type or an embedded type root interface: The root object that represents the criteria query, the query root of the criteria query defines the entity type, and the desired result is obtained for future navigation. It is similar to the FROM clause in SQL queries 1:root instances are typed and define the types that can occur in the FROM clause of a query. 2: The query root instance can be obtained by passing in an entity type to the Abstractquery.from method. 3:criteria queries, you can have multiple query roots. 4:abstractquery is the parent class of the Criteriaquery interface, which provides a way to get the root of the query. Criteriabuilder Interface: Builder object used to build Critiaquery predicate: a simple or complex predicate type, which is actually equivalent to a condition or a combination of conditions. criteria Query Base Object Build 1: Criteriabuilder Object 2 can be obtained by Getcriteriabuilder method of Entitymanager Getcriteriabuilder or entitymanagerfactory: by calling Criteriab The CreateQuery or Createtuplequery method of the Uilder can be used to obtain an instance of Criteriaquery 3: The root instance can be obtained by invoking the From method of Criteriaquery 1: Filter conditions are applied to the FROM clause of the SQL statement 。 In a criteria  query, the query condition is applied to the Criteriaquery object through a predicate or expression instance. 2: These conditions use the  criteriaquery .where  method to apply to criteriaquery  objects 3:criteriabuilder also as predicate instances of the factory, Create a predicate object by calling criteriabuilder  's conditional method ( equal,notequal, gt, ge,lt, le,between,like, and so on). 4: Composite predicate  statements can be built using the Criteriabuilder and, or andnot  method.   Build a simple predicate example: predicate p1=cb.like (Root.get ("name"). As (String.class), "%" +uqm.getname () + "%"); predicate p2=cb.equal (Root.get ("UUID"). As (Integer.class), Uqm.getuuid ()); predicate p3=cb.gt (Root.get ("age"). As (Integer.class), Uqm.getage ()); Build a combined predicate example: predicate p = Cb.and (P3,cb.or ( P1,P2);  Of course can also be shaped as the previous dynamic stitching query statements, such as:
    Specification<usermodel> spec = new specification<usermodel> () {public      predicate topredicate (Root <UserModel> root,              criteriaquery<?> query, Criteriabuilder CB) {          list<predicate> List = new Arraylist<predicate> ();                        if (Um.getname ()!=null && um.getname (). Trim (). Length () >0) {List.add (Cb.like (              root.get ("name"). As ( String.class), "%" +um.getname () + "%"));          }          if (Um.getuuid () >0) {              list.add (cb.equal (Root.get ("UUID"). As (Integer.class), Um.getuuid ()));          }          Predicate[] p = new predicate[list.size ()];          Return Cb.and (List.toarray (P));      }      ;  

You can also use Criteriaquery to come to the final predicate, as shown in the following example:

    Specification<usermodel> spec = new specification<usermodel> () {public          predicate topredicate (Root <UserModel> root,                  criteriaquery<?> query, Criteriabuilder CB) {              predicate p1 = Cb.like (Root.get (" Name "). As (String.class),"% "+um.getname () +"% ");              predicate P2 = cb.equal (Root.get ("UUID"). As (Integer.class), Um.getuuid ());              predicate p3 = cb.gt (Root.get ("age"). As (Integer.class), Um.getage ());              Apply predicate to Criteriaquery, because you can also add other functions to criteriaquery, such as sorting, grouping what Query.where (Cb.and (p3,cb.or              ));              Added the sorting function              Query.orderby (Cb.desc (Root.get ("UUID"). As (Integer.class)));                            return query.getrestriction ();          }      };  

multiple table joinsn Multi-table connection query A little more trouble, here is a demonstration of the common 1:m, incidentally 1:1n using the criteria query to implement 1-to-many query 1: First to add a solid object Depmodel, and set a good usermodel and its 1-to-many relationship, As follows: @Entity @table (name= "Tbl_user") public class Usermodel {@Idprivate integer uuid;private String name;private integer Age; @OneToMany (Mappedby = "um", fetch = Fetchtype. LAZY, cascade = {Cascadetype. All}) Private set<depmodel> setdep;//omit Getter/setter} @Entity @table (name= "TBL_DEP") public class Depmodel {@ Idprivate Integer uuid;private String name, @ManyToOne () @JoinColumn (name = "USER_ID", Nullable = False)//indicates that there is a US in TBL_DEP er_id fields Private Usermodel um = new Usermodel ();//Omit Getter/setter} 2: After configuring the model and its relationships, you can use it when building specification, Example below:specification<usermodel> spec = new specification<usermodel> () {public predicate topredicate (Root <UserModel> root, criteriaquery<?> query, Criteriabuilder CB) {predicate p1 = Cb.like (root.get ("name"). As ( String.class), "%" +um.getname () + "%"); predicate P2 = cb.equal (Root.get ("UUID"). As (Integer.class), Um.getuuid ()); predicate p3 = cb.gt (Root.get ("age"). As (Integer.class), Um.getage ()); setjoin<usermodel,depmodel> depjoin = Root.join (Root.getmodel (). Getset ("SETDEP", Depmodel.class), jointype.left); predicate P4 = cb.equal (Depjoin.get ("name"). As (String.class), "ddd"); //apply predicate to criteriaquery, because you can also add other functions to criteriaquery, such as sorting, grouping what of the Query.where (Cb.and (Cb.and (p3,cb.or (P1,P2)), p4));Adds a grouped feature Query.orderby (Cb.desc (Root.get ("UUID"). As (Integer.class)); return query.getrestriction ();}}; N Take a look at the criteria query to implement 1:1 of the query 1: Remove the SETDEP property and its configuration in Usermodel, and then add the following properties and configuration: @OneToOne () @JoinColumn (name = "Depuuid") Private Depmodel dep;public Depmodel getdep () {return DEP;}  public void Setdep (Depmodel dep) {THIS.DEP = dep; }2: The annotation configuration on the UM attribute in Depmodel is removed and replaced with the following configuration: @OneToOne (mappedby = "dep", Fetch = Fetchtype. EAGER, cascade = {Cascadetype. All}) 3: In the specification implementation, replace the setjoin sentence with the following:join<usermodel,depmodel> Depjoin =root.join (Root.getmodel (). Getsingularattribute ("DEP", Depmodel.class), Jointype.left)//root.join ("DEP", Jointype.left); This sentence is as simple as the function of the above sentence.

Learn spring Data JPA in layman's

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.