Some understandings about SPRING-DATA-JPA

Source: Internet
Author: User

Spring Data JPA Introduction First understand what JPA is?

JPA (Java Persistence API) is the Java Persistence specification proposed by Sun . It provides Java developers with an object/association mapping tool to manage relational data in Java applications. The main purpose of his presence is to simplify existing persistent development efforts and integrate ORM technology, and to end the current Hibernate,toplink,jdo and other ORM frameworks for each battalion. It is worth noting that JPA is developed on the basis of fully absorbing the existing HIBERNATE,TOPLINK,JDO and other ORM frameworks, with the advantages of ease of use and strong scalability. In response to the current development community, JPA has been greatly supported and praised, including the spring and EJB3.0 development teams.

Note:JPA is a set of specifications, not a set of products, then like hibernate,toplink,jdo they are a set of products, if these products implement this JPA specification, then we can call them to implement products for JPA .

Spring Data JPA

Spring Data JPA is a set of JPA application frameworks encapsulated on the basis of the ORM framework and JPA specifications of spring, enabling developers to access and manipulate data with minimalist code. It provides common functions including additions and deletions, and is easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency!

Spring data JPA frees us from the DAO layer operations, and basically all crud can rely on it to implement

Basic Query

The basic query is also divided into two, one is spring data by default has been implemented, one is based on the query method to automatically parse into SQL.

Pre-build method

Spring Data JPA defaults to pre-generating some basic curd methods, such as: Add, delete, change, etc.

1 Inheritance Jparepository

public interface UserRepository extends JpaRepository<User, Long> {}

2 Using the default method

@TestPublicvoidTestbasequery()ThrowsException{UserUser=NewUser();userrepository.. (1l. (user. (user.. (1l // ...               /span>                

It doesn't explain what you mean by the method name.

customizing simple Queries

A custom simple query is the automatic generation of SQL based on the method name, the main syntax being,,, followed by the findXXBy readAXXBy queryXXBy countXXBy getXXBy property name:

User findByUserName(String userName);

Also use some keywords plus some And ,Or

User findByUserNameOrEmail(String username, String email);

Modifications, deletions, and statistics are similar syntax

Long deleteById(Long id);Long countByUserName(String userName)

Basically the keywords in the SQL system can be used, for example: LIKE ,, IgnoreCase OrderBy .

List<User> findByEmailLike(String email);User findByUserNameIgnoreCase(String userName); List<User> findByUserNameOrderByEmailDesc(String email);

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)

Complex queries

In the actual development we need to use the paging, delete, and even the table query when you need a special method or custom SQL

Paging Query

Paged query in the actual use of the very common, spring data JPA has helped us achieve the function of paging, in the query method, the need to pass in Parameters Pageable , when the query has more than one parameter is Pageable recommended as the last parameter passed in

Page<User> findALL(Pageable pageable); Page<User> findByUserName(String userName,Pageable pageable);

Pageableis a spring-encapsulated paging implementation class that requires an incoming number of pages, a per-page count, and a collation

@TestPublicvoidTestpagequery()ThrowsException{IntPage=1,Size=10;SortSort=Newsort (direction. Desc "id" pageable pageable = new  Pagerequest (pagesizesortuserrepository. (pageableuserrepository. ( "testname" pageable               /span>                

restricting queries

Sometimes we just need to query the top n elements, or draw the previous entity.

SerFindfirstbyorderbylastnameasc();UserFindtopbyorderbyagedesc();Page<user> queryfirst10bylastname ( string lastnamepageable  Pageablelist<user>  Findfirst10bylastname (string lastnamesort sort); <user> findtop10bylastname  (string lastnamepageable pageable             
Custom SQL queries

In fact, most of the SQL in spring data can be implemented according to the method name definition, but for some reason we want to use custom SQL to query, spring data is also the perfect support;

Use annotations on SQL query methods @Query , such as those related to delete and modify when required @Modifying . You can also add @Transactional support for things, query timeout settings, etc. as needed.

@Modifying@Query("Update User u set u.username =? 1 where c.id =? 2")IntModifybyidanduserid(StringUserName, Long ID);  @Transactional@Modifying@Query("Delete from User where id =? 1")void Deletebyuserid (Long ID); @Transactional(timeout = ten)@Query("Select u from User u where u.emailaddress =? 1 ") User findbyemailaddress(String emailaddress);    
Multi-Table Query

There are two implementations of multi-table queries in spring data JPA, the first of which is implemented using Hibernate cascade queries, and the second is to create a result set interface to receive the results of a query with a table, the main second way.

You first need to define an interface class for a result set.

PublicInterfaceHotelsummary{city getcity (); getname () getaveragerating ()  Default integer getaverageratingrounded () {return getaveragerating () == null Span class= "O"? null :  (int)  Math. (getaveragerating ());                /span>                

The method return type of the query is set to the newly created interface

@Query("Select H.city as City, H.name as name, AVG (r.rating) as averagerating"- "from Hotel H left outer joins h.reviews r where h.city =? 1 Group by H"  pa Ge<hotelsummary> findbycity  (city citypageable pageable @Query  ( "select H.name as Name, AVG (r.rating) as averagerating" - "from Hotel H left Outer joins h.reviews R GROUP by H"  page
                           
                            <
                            hotelsummary> findbycity ( span class= "n" >pageable pageable       
                            

Use

Page<Hotelsummary>Hotels=This.hotelrepository. (new pagerequest (0< Span class= "O", 10direction. Asc (hotelsummary summay:hotels {system.. ( "Name" +summay. Getname              /span>                

In the run spring will automatically produce a proxy class for the interface (Hotelsummary) to receive the returned result, which is used in getXX the form of code summarization to get

Reproduced in: http://www.ityouknow.com/

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

Some understandings about 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.