Chapter One: Introduction to Spring Data JPA
What is Spring data
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 and 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 implementation is chosen Hibernate4 .2.0, a total of the following additional 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, Slf4j-api-1.7.3.jarn entity object, is the previous implementation mode @entity@table (name= "Tbl_user") public class Usermodel {@Idprivate Integer uuid;private String Name;privaTe integer age;//omits 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, which is equivalent to the DAO 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); The}n also needs to be configured in the spring configuration file, similar to the configuration using annotations: <?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "/http Www.springframework.org/schema/beans "xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance "xmlns:context=" http ://www.springframework.org/schema/context "xmlns:aop=" HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP "xmlns:tx=" http ://www.springframework.org/schema/tx "Xmlns:jpa=" Http://www.springframewoRK.ORG/SCHEMA/DATA/JPA "xsi:schemalocation=" Http://www.springframework.org/schema/beans/http Www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/context/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/CONTEXT/SPRING-CONTEXT-3.0.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/SPRING-AOP-3.0.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/SPRING-TX-3.0.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/DATA/JPA/HTTP Www.springframework.org/schema/data/jpa/spring-jpa.xsd "><context:component-scan base-package=" Cn.javass " ><context:exclude-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/>< /context:component-scan><aop:aspectj-autoproxy proxy-target-class= "true"/><!--open annotation transaction is only valid for the current profile-- ><tx:annotation-driven transaction-manager= "TransactionManager" proxy-target-class= "true"/>
<jpa:repositories
base-package= "Cn.javass"
repository-impl-postfix= "Impl"
entity-manager-factory-ref= "Entitymanagerfactory"
transaction-manager-ref= "TransactionManager" >
</jpa:repositories>
<bean id= "Entitymanagerfactory"
class= "Org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > <property name= "DataSource" ref= "DataSource"/> <property name= "Packagestoscan" value= "Cn.javass"/> <property name= "Persistenceprovider" > <bean class= "Org.hibernate.ejb.HibernatePersistence"/> </property> <property name= "Jpavendoradapter" > <bean class= " Org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter "> <property name= "Generateddl" value= "false"/> <property name= "Database" value = "MYSQL"/> <property name= "DatabasePlatform" value= " Org.hibernate.dialect.MySQL5InnoDBDialect "/> <property name= "Showsql" value= "true"/> </bean> </property> <property name= "Jpadialect" > <bean class= "Org.springframework.orm.jpa.vendor.HibernateJpaDialect"/> </property> <property name= " Jpapropertymap "> <map> <entry key= " Hibernate.query.substitutions"Value=" True 1, False 0 "/> <entry key= "hibernate.default_batch_fetch_size" value= "/> " <entry key= "hibernate.max_fetch_depth" value= "2"/> <entry key= " Hibernate.generate_statistics "value=" true "/> <entry key= "Hibernate.bytecode.use_reflection_optimizer" value= "true"/> <entry key= " Hibernate.cache.use_second_level_cache "value=" false "/> <entry key= "Hibernate.cache.use_query_cache" value= "false"/> </map> </property > </bean><!--transaction manager configuration--> <bean id= "TransactionManager" class= "Org.springframework.orm.jpa.JpaTransactionManager" > <property Name= "Entitymanagerfactory" ref= "entitymanagerfactory"/> </bean> <bean name= " DataSource "class=" Org.apache.commons.dbcp.BasicDataSource "><property name=" Driverclassname "><value >org.gjt.mm.mysql.driver</value></property><property name= "url" ><value>jdbc:mysql:// Localhost:3306/cc?useunicode=true&characterencoding=utf-8</value></property><property Name= "username" > <value>root</value> </property><property name= "password" value= "cc"/> </bean></beans> after the configuration is complete, you can run the client test, of course, the database and tables need to be ready or add filter under <jpa:repositories>, shaped like: <repositories base-package= "com.acme.repositories" ><context:exclude-filter type= "regex" expression= " . *somerepository "/></repositories> 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, can not write implementation, the currently supported keywords are as follows:
The Spring Data JPA Framework, when parsing a method name, first intercepts the extra prefixes of the method name, such as Find, FindBy, read, Readby, get, Getby, and then parses the rest.
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: DAO's reposit in its own implementation The Ory interface defines a method with the same name, as shown in the following example: Public list<usermodel> findbyage (int age); 3: Then it can be used, and spring will first find out if there is a namedquery of the same name, if any, Then you will not follow upmethod to parse the port definition. 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; 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
Java code:
View Copy to clipboard print public class Userrepositoryimpl {@PersistenceContext private entitymanager em; public page<object []> getbycondition (Userquerymodel u) {String hql = "Select O.uuid,o.name from Usermodel o where 1=1 and O.uuid=:uui D "; 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
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 QueryBase 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 the 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 is applied to the Criteriaquery object 3:criteriabuilder also as the factory of the predicate instance, by calling the Criteriabuilder conditional method ( Equal,notequal, GT, Ge,lt, le,between,like, etc.) create predicate objects. 4: Composite predicate statements can be constructed using Criteriabuilder's and, or Andnot methods. 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, it can be shaped like the previous dynamic stitching query statements, such as:
Java code:
You can also use Criteriaquery to come to the final predicate, as shown in the following example:
Java code:
Multiple table joins
n 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.
Excerpt from: The original source of the garden can't put it up sorry! ~
Learn spring Data JPA in layman's