Spring Data Jpa Initial Case and Query Detailed Analysis (in-depth good text)

 SpringDataJpaSpring Data JPA

Let's get rid of the operation of DA0 layer, basically all CRUD s can rely on it to achieve. In practical work projects, Spring Data JPA+ORM (e.g. hibernate) is recommended to complete the operation, which provides great convenience in switching different ORM frameworks, but also makes the operation of database layer simpler and more convenient. Decoupling.

 

Encapsulating the code of JPA specification, it is hibernate or mybatis >> (encapsulating jdbc operation) that queries or operates database.

Spring Data Jpa Initial Operations (Setting up Environment)

Create a project and import coordinates

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 <project xmlns="http://maven.apache.org/POM/4.0.0"
  3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4          xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5     <modelVersion>4.0.0</modelVersion>
  6 
  7     <groupId>cn.itcast</groupId>
  8     <artifactId>jpa-day02</artifactId>
  9     <version>1.0-SNAPSHOT</version>
 10 
 11     <properties>
 12         <spring.version>5.0.2.RELEASE</spring.version>
 13         <hibernate.version>5.0.7.Final</hibernate.version>
 14         <s1f4j.version>1.6.6</s1f4j.version>
 15         <log4j.version>1.2.12</log4j.version>
 16         <c3pe.version>0.9.1.2</c3pe.version>
 17         <mysql.version>5.1.6</mysql.version>
 18     </properties>
 19 
 20     <dependencies>
 21         <!--junit unit testing-->
 22         <dependency>
 23             <groupId>junit</groupId>
 24             <artifactId>junit</artifactId>
 25             <version>4.9</version>
 26             <scope>test</scope>
 27         </dependency>
 28         <!--spring beg-->
 29         <dependency>
 30             <groupId>org.aspectj</groupId>
 31             <artifactId>aspectjweaver</artifactId>
 32             <version>1.6.8</version>
 33         </dependency>
 34         <dependency>
 35             <groupId>org.springframework</groupId>
 36             <artifactId>spring-aop</artifactId>
 37             <version>${spring.version}</version>
 38         </dependency>
 39         <dependency>
 40             <groupId>org.springframework</groupId>
 41             <artifactId>spring-context</artifactId>
 42             <version>${spring.version}</version>
 43         </dependency>
 44         <dependency>
 45             <groupId>org.springframework</groupId>
 46             <artifactId>spring-context-support</artifactId>
 47             <version>${spring.version}</version>
 48         </dependency>
 49         <!--spring Yes ORm Framework support packages-->
 50         <dependency>
 51             <groupId>org.springframework</groupId>
 52             <artifactId>spring-orm</artifactId>
 53             <version>${spring.version}</version>
 54         </dependency>
 55         <dependency>
 56             <groupId>org.springframework</groupId>
 57             <artifactId>spring-beans</artifactId>
 58             <version>${spring.version}</version>
 59         </dependency>
 60         <dependency>
 61             <groupId>org.springframework</groupId>
 62             <artifactId>spring-core</artifactId>
 63             <version>${spring.version}</version>
 64         </dependency>
 65 
 66         <!--spring end-->
 67 
 68         <!--hibernate beg-->
 69         <dependency>
 70             <groupId>org.hibernate</groupId>
 71             <artifactId>hibernate-core</artifactId>
 72             <version>${hibernate.version}</version>
 73         </dependency>
 74         <dependency>
 75             <groupId>org.hibernate</groupId>
 76             <artifactId>hibernate-entitymanager</artifactId>
 77             <version>${hibernate.version}</version>
 78         </dependency>
 79         <dependency>
 80             <groupId>org.hibernate</groupId>
 81             <artifactId>hibernate-validator</artifactId>
 82             <version>5.2.1.Final</version>
 83         </dependency>
 84 
 85         <!--hibernate end-->
 86 
 87         <!--c3p0 beg-->
 88         <dependency>
 89             <groupId>c3p0</groupId>
 90             <artifactId>c3p0</artifactId>
 91             <version>0.9.1.2</version>
 92         </dependency>
 93 
 94         <!--log end-->
 95         <dependency>
 96             <groupId>log4j</groupId>
 97             <artifactId>log4j</artifactId>
 98             <version>1.2.17</version>
 99         </dependency>
100         <dependency>
101             <groupId>org.slf4j</groupId>
102             <artifactId>slf4j-api</artifactId>
103             <version>1.7.25</version>
104         </dependency>
105         <dependency>
106             <groupId>org.slf4j</groupId>
107             <artifactId>slf4j-log4j12</artifactId>
108             <version>1.6.6</version>
109         </dependency>
110         <!--log end-->
111 
112         <dependency>
113             <groupId>mysq1</groupId>
114             <artifactId>mysql-connector-java</artifactId>
115             <version>5.1.6</version>
116         </dependency>
117         <!-- spring data jpa Coordinates of -->
118         <dependency>
119             <groupId>org.springframework.data</groupId>
120             <artifactId>spring-data-jpa</artifactId>
121             <version>1.9.0.RELEASE</version>
122         </dependency>
123         <dependency>
124             <groupId>org.springframework</groupId>
125             <artifactId>spring-test</artifactId>
126             <version>4.2.4.RELEASE</version>
127         </dependency>
128 
129         <!--el beg Use spring data jpa Must be introduced-->
130         <dependency>
131             <groupId>javax.el</groupId>
132             <artifactId>javax.el-api</artifactId>
133             <version>2.2.4</version>
134         </dependency>
135         <dependency>
136             <groupId>org.glassfish.web</groupId>
137             <artifactId>javax.el</artifactId>
138             <version>2.2.4</version>
139         </dependency>
140         <dependency>
141             <groupId>org.projectlombok</groupId>
142             <artifactId>lombok</artifactId>
143             <version>1.16.22</version>
144         </dependency>
145     </dependencies>
146 </project>
Dependent coordinates required for the project

Configure Spring's configuration file

 1 <!--Establish entityManagerFactory Object Delivery Spring Container management-->
 2     <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">   (Permission Location Class Name)
 3         <property name="dataSource" ref="dataSource"/>     (Dependency Injection)
 4         <property name="packagesToScan " value="cn.itcast.domain"/>   (Configured scanned packages, packages where entity classes reside)
 5         <property name="persistenceProvider">  (JPA Implementing manufacturer)
 6             <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
 7         </property>
 8 
 9         <!--jpa Supplier adapter-->
10         <property name="jpaVendorAdapter">
11             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
12                 <!--Configure whether to automatically create database tables-->
13                 <property name="generateDdl" value="false"/>
14                 <!--Specify database type-->
15                 <property name="database" value="MYSQL"/>
16                 <!--Database Dialect: Supported Specific Grammar (Different databases have different grammars)-->
17                 <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
18                 <!--Whether to display sql-->
19                 <property name="showSql" value="true"/>
20             </bean>
21         </property>
22 
23         <!--jpa Dialect: Advanced Characteristics(Whoever configures has advanced features.-->
24         <property name="jpaDialect">
25             <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"></bean>
26         </property>
27     </bean>
28     <!--2.Create a database connection pool-->
29     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
30         <property name="user" value="root"></property>
31         <property name="password" value="123456"></property>
32         <property name="jdbcUrl" value="jdbc:mysq1:///jpa"></property>
33         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
34     </bean>
35 (The following do not require special memory)>>>
36     <!--3.integration spring dataJpa-->
37     <jpa:repositories base-package="cn.itcast.dao" transaction-manager-ref="transactionManager"
38                       entity-manager-factory-ref="entityManagerFactory"></jpa:repositories>
39     <!--4.Configuring Transaction Manager-->
40     <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
41         <property name="entityManagerFactory" ref="entityManagerFactory"></property>
42     </bean>
43     <!--5.Declarative transaction-->
44     <!--6.Configuration package scanning-->
45     <context:component-scan base-package="cn.itcast"></context:component-scan>
46 </beans>

Writing dao layer interface conforming to Spring Data Jpa specification

 1 package cn.itcast.dao;
 2 
 3 import cn.itcast.domain.Customer;
 4 
 5 import org.springframework.data.jpa.repository.JpaRepository;
 6 import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
 7 /**
 8  * dao Layer Interface Specification for Spring Data Jpa
 9  * JpaRepository<Entity class type of operation, type of primary key attribute in entity class) >> encapsulates basic CRUD operations
10  * JpaSpecificationExecutor<Entity class type of operation > > > > > > > > > encapsulates complex queries ()
11  */
12 public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {}

 

Complete the Client's Addition, Deletation, Amendment and Examination Operation

Query by id

em.find() loads immediately

@ Transactional: Ensure getOne works properly

em.getReference() Delayed Loading > > > Returns a customer's dynamic proxy object, when to use and when to query

1 @Test
2     public void testFindOne() {
3         Customer customer = customerDao.findOne(3l);
4         System.out.println(customer);
5     }

 

sava

1 @Test
2     public void testSave() {
3         Customer customer = new Customer();
4         customer.setCustname("Black Horse Programmer");
5         customer.setCustaddress("Beijing");
6         customer.setCustindustry("IT education");
7         customerDao.save(customer);
8     }
1 @Test
2     public void testUpdate() {
3         Customer customer = new Customer();
4         customer.setCustid(1l);
5         customer.setCustname("Podcast");
6         customer.setCustindustry("Dark horse programmers are very good");
7         customerDao.save(customer);
8     }

 

Delete (delete) by id

1 @Test
2     public void testDelete() {
3         Customer customer = new Customer();
4         customerDao.delete(1l);
5     }

 

Find All

1 @Test
2     public void findAll(){
3         List<Customer> list = customerDao.findAll();
4         for (Customer customer : list) {
5             System.out.println(customer);
6         }

 

Running Process and Principle Analysis of Spring Data Jpa

1. Create a dynamic proxy object by invoke method of JdkDynamicAopProxy
2. The operation of JPA is encapsulated in simple Jpa Repository (CRUD of database is completed by JPA api)
3. Complete database operation through hibernate (encapsulated jdbc)

Complex queries

findone (id): Query by ID

Test Statistical Query: Query the Total Number of Customers

1 @Test
2     public void testdount() {
3         long count = customerDao.count();//Query the total number of customers System.out.println(count);
4         System.out.println(count);
5     }

Testing: Determining if a customer with id 3 exists

If the value is empty, the representative does not exist, if not empty, the representative exists.

If the quantity is 0, it means that there is no (false) and if it is greater than 0, it means that there is (true)

1 @Test
2     public void testExists() {
3         boolean exists = customerDao.exists(3l);
4         System.out.println(exists);
5     }

 

 

 

 

jpql: jpa query language (jpq query language)

Features: Grammar or keywords are similar to sql statements
Queries are for attributes in classes and classes

JPQL statements need to be configured on the interface method

1. Specific queries: methods need to be configured on the dao interface

2. Configure the jpql query statement in the form of annotations on the newly added method
Note: @Query

Case: Query by customer name >> using Jpql

CustomerDao

 

1 public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {
2     /**
3      * Case study: Search name according to customer name
4      *      Formal Query Using Jpql
5      *      jpql:  from Customer where custName = ?
6      */
7     @Query(value = "from Customer where custname = ?")
8     public Customer findJpql(String custname);
9 }

 

 

 

 JpqlTest

1 @Test
2     public void testFindJpql(){
3         Customer customer = customerDao.findJpql("Wisdom transmission");
4         System.out.println(customer);
5     }

 

Case Study: Query Customers by Customer Name and Customer id > Use Jpql to Query

 

    @Query(value="from Customer where custName=? and custId=?")
    public Customer findCustNameAndId (String name , Long id );

    @Query (value=" from Customer where custName = ?2 and custId = ?1 ")

    public Customer findCustNameAndId ( Long id , String name );

CustomerDao

1 @Query(value = "from Customer where custname = ? and custid = ?")
2     public Customer findCustNameAndId(String custname, long id);

 JpqlTest   

1 @Test
2     public void testCustNameAndId(){
3         Customer customer = customerDao.findCustNameAndId("Dark horse",2l);
4         System.out.println(customer);
5     }

Use jpql to complete the update operation case: update the name of customer 2 according to id, change the name to "black horse programmer"

CustomerDao

1 @Query(value = " update Customer set custname = ?2 where custid = ?1 ") //Represents queries.
2     @Modifying //The current execution is an update operation
3     //Update does not require return value to select void
4     public void UpdateCustomer( long custid,String custname);

 JpqlTest  

1 @Test
2     @Transactional //Adding transaction support
3     @Rollback(value = false) //Set whether to roll back automatically
4     public void testUpdateCustomer(){
5         customerDao.UpdateCustomer(2l,"Black Horse Programmer");
6     }

After execution, the transaction is rolled back by default and can be automatically rolled back by setting @Rollback >> false | true

 

1. Specific queries: methods need to be configured on the dao interface

2. Configuring sql query statements in the form of annotations in the newly added method
Note: @Query

      value: jsql   |  sql

NativeQuery: FALS (using jpql query) l. true (using local query: sql query)

CustomerDao

1 @Query(value = "select * from cst_customer",nativeQuery = true)
2     public List<Object[]>findSql();

 JpqlTest 

1 @Test
2     public void testfindSql(){
3         List<Object[]> list = customerDao.findSql();
4         for (Object[] obj : list) {
5             System.out.println(Arrays.toString(obj));//Every one is still inside. object Arrays, so you need help Arrays.toString()MethodPrint arrays
6         }

 

> 1: findBy + attribute name (capital initials)

 

 

public Customer findByCustname(String custname);

 

 

 

1 @Test
2     public void testNaming(){
3         Customer customer = customerDao.findByCustname("Wisdom transmission");
4         System.out.println(customer);
5     }

 

>> 2: findBy + Attribute Name (Capitalization) + "Query Mode"

public List<Customer> findByCustnameLike(String custname);
1 @Test
2     public void testfindByCustnameLike(){
3         List<Customer> list = customerDao.findByCustnameLike("Dark horse%");
4         for (Customer customer : list) {
5             System.out.println(customer);
6         } }

 

> 3: findBy + attribute name (capitalization) + "query mode" + "multi-condition connector (and | or) +"attribute name"+"query mode"

Queries using vague matching of customer names and precise matching of customer industries

public List<Customer> findByCustnameLikeAndCustindustry(String custname, String custindustry); //The result may be one or more, so chooseList<Customer>

 

1 @Test
2     public void testFindByCustnameLikeAndCustindustry(){
3         List<Customer> list = customerDao.findByCustnameLikeAndCustindustry("Dark horse%","it education");
4         for (Customer customer : list) {
5             System.out.println(customer);
6         } }

 

 

Specifications dynamic query

Public Predicate to Predicate (Root < Customer > root, Criteria Query <?> query, Criteria Builder cb) {} // Encapsulate query conditions

 

Query customers named "Chuanzhi"

 1 @Test
 2     public void testSpec() {
       Realization Specification Interface( Provide generics : Object attributes of queries)
3 Specification<Customer> spec = new Specification<Customer>() {
       Realization toPredicate Method (Constructing Query Conditions)
4 public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) { 5 //1.Get the properties of the comparison 6 Path<Object> custname = root.get("custname"); 7 //2.Constructing query conditions 8 Predicate predicate = cb.equal(custname, "Wisdom transmission"); //Precise matching (custname: attribute of comparison, intellectual transmission: value of attribute of comparison) 9 return predicate; 10 }}; 11 Customer customer = customerDao.findOne(spec); 12 System.out.println(customer); 13 }

Query customers named "Black Horse 2" and whose industry is "it education"

 1 @Test
 2     public void testSpec1() {
 3         Specification<Customer> spec = new Specification<Customer>() {
 4             public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
 5                 //1.Get the properties of the comparison
 6                 Path<Object> custname = root.get("custname");
 7                 Path<Object> custindustry = root.get("custindustry");
 8                 //2.Constructing query conditions
 9                 Predicate p1 = cb.equal(custname, "Black Horse 2");
10                 Predicate p2 = cb.equal(custindustry, "it education");
           and(Relationships):Satisfies condition 1 and satisfies condition 2 or(Or relationship): Satisfies condition 1 or satisfies condition 2
11 Predicate and = cb.and(p1, p2); 12 return and; 13 } 14 }; 15 Customer customer = customerDao.findOne(spec); 16 System.out.println(customer); 17 }

 

Case: Complete the fuzzy matching according to the customer name, return the customer list > > customer name to start with "Smart Podcast"

Default: equal: Get the path object (attribute) directly, and then compare it.

gt (greater), lt (less than), ge (greater than or equal), le (less than or equal), like: get the path object, specify the parameter type of comparison according to the path, and then compare.

Specify parameter type: path.as (type bytecode object)

 

 1 @Test
 2     public void testSpec2() {
 3         Specification<Customer> spec = new Specification<Customer>() {
 4             public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
 5                 Path<Object> custname = root.get("custname");  //Query Properties: Customer Name
 6                 Predicate predicate = cb.like(custname.as(String.class), "Wisdom Podcast%"); //Query Mode: Fuzzy Matching
 7                 return predicate;
 8             }
 9         };
10         List<Customer> list = customerDao.findAll(spec);
11         for (Customer customer : list) {
12             System.out.println(customer);
13         } }

Add Sort > > Create Sort Object, you need to call the constructor to instantiate the sort object

First parameter: order of sorting (reverse, positive)

Second parameter: Sort property name

1   Sort sort = new Sort(Sort.Direction.DESC, "custid");
2   List<Customer> list = customerDao.findAll(spec, sort);

 

 

Paging queries

In the process of creating PageRequest, you need to call his constructor to pass in two parameters

First parameter: the number of pages in the current query (starting from e)

Second parameter: the number of queries per page

 

 1 @Test
 2     public void testSpec3() {
 3         Specification spec = null; //No parameters
 4         Pageable pageable = new PageRequest(0, 2);
 5         //Paging query
 6         Page<Customer> page = customerDao.findAll(null, pageable);
 7         System.out.println(page.getContent());//Get a list of data sets
 8         System.out.println(page.getTotalElements());//Get the total number of entries
 9         System.out.println(page.getTotalPages());//Get the total number of pages
10     }

 

 1 @Test
 2     public void testSpec4() {
 3         Specification spec = new Specification() {
 4             public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
 5                 Path custname = root.get("custname");
 6                 Predicate predicate = criteriaBuilder.equal(custname, "Wisdom Podcast");
 7                 return predicate;
 8             }};
 9         Pageable pageable = new PageRequest(0, 2);
10         //Paging query
11         Page<Customer> page = customerDao.findAll(spec, pageable);
12         System.out.println(page.getContent());//Get a list of data sets
13         System.out.println(page.getTotalElements());//Get the total number of entries
14         System.out.println(page.getTotalPages());//Get the total number of pages
15     }

Tags: Java Spring Hibernate Database Attribute

Posted on Sun, 08 Sep 2019 06:41:52 -0700 by Glyde