Spring-boot (iii) spring data JPA

Source: Internet
Author: User
Tags mongodb support

Learn article from: Http://www.ityouknow.com/spring-boot.htmlspring 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 extends Jparepository<user, long> {}

2 Using the default method

@Test  Public void throws Exception {    user user=new  User ();    Userrepository.findall ();    Userrepository.findone (1l);    Userrepository.save (user);    Userrepository.delete (user);    Userrepository.count ();    Userrepository.exists (1l);     //  ...}

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

@Test  Public void throws Exception {    int page=1,size=10;     New Sort (DIRECTION.DESC, "id");     New pagerequest (page, size, sort);    Userrepository.findall (pageable);    Userrepository.findbyusername ("testname", pageable);}

restricting queries

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

ser findfirstbyorderbylastnameasc (); User Findtopbyorderbyagedesc (); Page<User> queryfirst10bylastname (String LastName, pageable pageable); List<User> findfirst10bylastname (String LastName, sort sort); List<User> Findtop10bylastname (String LastName, pageable pageable);

Custom SQL queries

In fact, most of the SQL of 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 is related to deletion and modification in need @Modifying of adding. You can also add @Transactional support for things as needed, query timeout settings, etc.

@Modifying @query ("Update User u set u.username =? 1 where u.id =? 2") int Modifybyidanduserid (String  userName, Long ID);    @Transactional @modifying@query ("Delete from User where id =? 1")void  Deletebyuserid (Long ID );   = Ten) @Query ("Select u from user u where u.emailaddress =? 1")    User findbyemailaddress (String Emailad Dress);

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.

 Public Interface hotelsummary {city    getcity ();    String getName ();    Double getaveragerating ();     default Integer getaverageratingrounded () {        returnnullnull : (int ) Math.Round (getaveragerating ());}    }

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 join h.reviews r where h.city = ?1 group by h")Page<HotelSummary> findByCity(City city, Pageable pageable);@Query("select h.name as name, avg(r.rating) as averageRating "- "from Hotel h left outer join h.reviews r  group by h")Page<HotelSummary> findByCity(Pageable pageable);

Use

Page<HotelSummary> hotels = this.hotelRepository.findByCity(new PageRequest(0, 10, Direction.ASC, "name"));for(HotelSummary summay:hotels){System.out.println("Name" +summay.getName());}

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

Multi-source support for multiple data sources supporting homogeneous databases

Because of the distributed development pattern used in daily projects, different services have different data sources, often need to use multiple data sources in one project, so it is necessary to configure the use of sping data JPA for multiple data sources, which is generally divided into three steps:

    • 1 Configuring multiple data sources
    • 2 entity classes of different sources into different package paths
    • 3 declaring different package paths using different data sources, transaction support

Here is an article that is very clear: Spring boot multi-data source configuration and use

Heterogeneous database multi-source support

For example, in our project, we need support for MySQL, as well as a query for MongoDB.

Entity classes declare @Entity relational database support types, declared @Document as MongoDB support types, and different data sources use different entities to

interface PersonRepository extends Repository<Person, Long> { …}@Entitypublic class Person {  …}interface UserRepository extends Repository<User, Long> { …}@Documentpublic class User {  …}

However, if user users use both MySQL and MongoDB, they can also do mixed use

interface JpaPersonRepository extends Repository<Person, Long> { …}interface MongoDBPersonRepository extends Repository<Person, Long> { …}@Entity@Documentpublic class Person {  …}

You can also declare different package paths, such as using MongoDB under the Mysql,b package path under a packet path

@EnableJpaRepositories(basePackages = "com.neo.repositories.jpa")@EnableMongoRepositories(basePackages = "com.neo.repositories.mongo")interface Configuration { }

Other

Using enumerations

When using enumerations, we want the database to store an enumeration of the corresponding string type, rather than the index value of the enumeration, to add annotations to the attribute @Enumerated(EnumType.STRING)

@Enumerated(EnumType.STRING) @Column(nullable = true)private UserType type;

Properties that do not need to be mapped with the database

Normally when we add annotations to an entity class @Entity , we make the entity class and the table related if one of the properties we do not need to associate with the database is just a calculation at the time of the presentation, just add the @Transient attribute.

@Transientprivate String  userName;

学习文章来自:Springboot (v): Use of spring data JPA
耽误了两天,又开始学习了!
由于我的前端框架是easyui,就没有记录学习
Thymeleaf I also want to mybatis about SQL.

Spring-boot (iii) 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.