Vii. Integration of Springboot SPRING-DATA-JPA

Source: Internet
Author: User

What is 1.Spring Data JPA

A framework provided by spring for simplifying JPA development. Access to and manipulation of data can be achieved with virtually no write implementation. In addition to CRUD, it also includes some common functions such as paging, sorting, etc.

Core concepts of 1.Spring Data JPA:

1:repository: The topmost interface, which is an empty interface, is designed to unify all types of Repository and to automatically recognize components as they are scanned.

2:crudrepository: is a repository sub-interface that provides CRUD functionality

3:pagingandsortingrepository: is a crudrepository sub-interface that adds pagination and sorting functionality

4:jparepository: Is the Pagingandsortingrepository sub-interface, added some useful functions, such as: batch operation.

5:jpaspecificationexecutor: Used to do the interface responsible for querying

6:specification: is a query specification provided by Spring Data JPA, to make complex queries, simply set the query criteria around this specification to

2. Jparepository's query

Specific keywords, using methods and production into SQL are shown in the following table

Keyword Sample JPQL Snippet
and Findbylastnameandfirstname ... where x.lastname =? 1 and x.firstname =? 2
Or Findbylastnameorfirstname ... where x.lastname =? 1 or x.firstname =? 2
Is,equals Findbyfirstnameis,findbyfirstnameequals ... where x.firstname =? 1
Between Findbystartdatebetween ... where x.startdate between? 1 and? 2
LessThan Findbyagelessthan .. where X.age <? 1
Lessthanequal Findbyagelessthanequal ... where x.age?? 1
GreaterThan Findbyagegreaterthan .. where X.age >? 1
Greaterthanequal Findbyagegreaterthanequal ... where x.age >=? 1
After Findbystartdateafter .. where X.startdate >? 1
Before Findbystartdatebefore .. where X.startdate <? 1
IsNull Findbyageisnull ... where x.age is null
Isnotnull,notnull Findbyage (IS) notnull ... where x.age not null
Like Findbyfirstnamelike ... where x.firstname like? 1
Notlike Findbyfirstnamenotlike ... where x.firstname not? 1
Startingwith Findbyfirstnamestartingwith ... where x.firstname like? 1 (parameter bound with appended%)
Endingwith Findbyfirstnameendingwith ... where x.firstname like? 1 (parameter bound with prepended%)
Containing Findbyfirstnamecontaining ... where x.firstname like? 1 (parameter bound wrapped in%)
By Findbyageorderbylastnamedesc ... where x.age =? 1 ORDER BY X.lastname DESC
Not Findbylastnamenot .. where X.lastname <>? 1
Inch Findbyagein (Collection Ages) ... where x.age in? 1
Notin Findbyagenotin (Collection Age) ... where x.age not in? 1
TRUE Findbyactivetrue () ... where x.active = True
FALSE Findbyactivefalse () ... where x.active = False
IgnoreCase Findbyfirstnameignorecase ... where UPPER (x.firstame) = UPPER (? 1)

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 the following query is created: Findbyuserdepuuid (), when the framework parses the method, it first rejects the findBy and then parses the remaining attributes, assuming the query entity is doc

1: First Judge Userdepuuid (according to the POJO specification, the first letter to lowercase) is a property of the query entity, if it is, the query based on the property, or if there is no property, continue the second step;

2: The string that starts with the first capital letter from right to left is the UUID, and then checks whether the remaining string is a property of the query entity, or, if it is, a query based on that property, and if not, repeats the second step, continuing from right to left Finally, assume that the user is a property of the query entity;

3: Then processing the remainder (DEPUUID), first determine whether the user's corresponding type has DEPUUID attribute, if there is, it means that the method is ultimately based on the value of "Doc.user.depUuid" query, otherwise continue to follow the rules of step 2 from right to left intercept, The result is 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 an 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);

You can also use the JPA namedqueries, as follows:

1: Use @namedquery on the entity class, as shown in the following example:

@NamedQuery (name = "Usermodel.findbyage", query = "Select O from Usermodel o where o.age >=? 1")

2: Define a method of the same name in the Repository interface of the DAO that you implement, with the following example:

Public list<usermodel> Findbyage (int.);

3: Then it can be used, and spring will first 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.

Use @Query

You 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);

Attention:

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 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, it is not wrong to add

n You can also use @query to specify local queries, as long as you set Nativequery to True, such as:

@Query (value= "select * from Tbl_user where name is 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 named parameters, you can use @param, for example:

@Query (value= "Select O from Usermodel o where o.name like%:nn")

Public list<usermodel> Findbyuuidorage (@Param ("nn") String name);

Also support for updating the query statement of the class, add @modifying can, 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);

Attention:

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 at the place of invocation, no transaction can be performed normally

jparepository the query function

Order of creation of queries

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 cases available at the same time?

<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 found, uses the named query; 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 a named query is compliant, or the method is passed @Query the specified query statement, it will be ignored

3:use-declared-query: 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 found, uses the named query; throws an exception if neither is found

   3.Specifications QuerySpring Data JPA supports the criteria query for JPA2.0, and 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)); 2. Integration with Springboot

Maven:

< Dependency     <groupid >org.springframework.boot</groupId>    <  Artifactid>spring-boot-starter-data-jpa</artifactid>  </dependency>

Gradle

dependencies {        compile (' ORG.SPRINGFRAMEWORK.BOOT:SPRING-BOOT-STARTER-DATA-JPA ')      }

Note: you need to configure the data source

JPA Optional Configuration

spring.jpa.database=spring.jpa.show-sql=spring.jpa.properties=spring.jpa.generate-ddl=spring.jpa.open-in-view= Spring.jpa.database-platform=spring.jpa.hibernate.ddl-auto=spring.data.jpa.repositories.enabled= spring.jpa.hibernate.naming-strategy=
3. Part of the Java code in the project
@NoRepositoryBean  Public Interface extends Jparepository<t, String>, jpaspecificationexecutor<t> {    }
 Public Interface extends Daointerface<jdcommoditybean> {        /**     * Paged Query products           */ Page<JDCommodityBean> findAll (specification<jdcommoditybean> spec, pageable pageable);}
@Transactional (rollbackfor = Exception.class) @Service Public classJdcommodityserviceimplextendsBaseservice<jdcommoditybean>ImplementsJdcommodityservice {@PersistenceContextPrivateEntitymanager Entitymanager; @AutowiredPrivatejdcommodityrepository jdcommodityrepository; @Override PublicPage<jdcommoditybean>getjdcommoditylistbypage (Integer pagenum, string name, String goodscategory) {specification<JDCommodityBean> spec =NewSpecification<jdcommoditybean>() {            /*** Construct Assertion * *@paramroot * Entity Object reference *@paramquery * Rule Queries Object *@paramCB * Rule Building Object *@returnAssertion*/@Override Publicpredicate topredicate (root<jdcommoditybean> Root, criteriaquery<?>query, Criteriabuilder CB) {List<Predicate> predicates =NewArraylist<> ();//all the Assertions collection//defaultPredicates.add (Cb.equal (Root.get ("state"). As (Integer.class), 1));//Upper and lower frame status 1 is on shelves, 0 for bottom shelfPredicates.add (Cb.equal (Root.get ("Salestate"). As (Integer.class), 1));//can be sold, 1: Yes, 0: noPredicates.add (Cb.equal (Root.get ("Iscanvat"). As (Integer.class), 1));//whether to open an additional ticket, 1: Support, 0: not supportedPredicates.add (Cb.le (Root.get ("price"). As (BigDecimal.class), 500));//Price is less than or equal to//Custom//Product Name                if(NULL! = name &&! "". Equals (name) &&! "". Equals (name) && name! = "") {Predicates.add (Cb.like (Root.get ("Name"). As (String.class), "%" + name + "%")); }                //Product Categories                if(Goodscategory! =NULL&& "". Equals (goodscategory) &&! "". Equals (Goodscategory)) {Predicates.add (Cb.equal (Root.get ("Goodscategory"). As (String.class) , goodscategory)); }                returnCb.and (Predicates.toarray (Newpredicate[predicates.size ()]);        }        }; pageable pageable=NewPagerequest (PageNum-1, jdcommonconstant.commodity_page_size);//page Number: Front end starting from 1, JPA starting from 0page<jdcommoditybean> page =Jdcommodityrepository.findall (spec, pageable); returnpage; } @OverrideprotectedEntitymanager Getentitymanager () {returnEntitymanager; } @OverrideprotectedDaointerface<jdcommoditybean>Getdaointerface () {returnjdcommodityrepository; }}

Reference:

Https://legacy.gitbook.com/book/ityouknow/spring-data-jpa-reference-documentation/details

Http://www.ityouknow.com/springboot/2016/08/20/springboot (%e4%ba%94)-spring-data-jpa%e7%9a%84%e4%bd%bf%e7%94% A8.html

Vii. Integration of Springboot SPRING-DATA-JPA

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.