SpringBoot2.x series of tutorials - integrated use of JPA

1. Introduction to JPA

1. JPA concept

JPA is the Java Persistence Specification officially proposed by Sun. It is the abbreviation of Java Persistence API. The Chinese name is 'Java Persistence Layer API'. It is essentially an ORM specification.

JPA describes the mapping relationship of 'object-relational table' through JDK 5.0 annotations or XML, and persists the runtime entity objects into the database.

2. The reason for the emergence of JPA

Sun introduced the JPA specification for two reasons:

    1. Simplify the development of existing Java EE and Java SE;
    1. Sun hopes to integrate ORM technology to realize the unity of the world.

In other words, the purpose of Sun's proposed JPA specification is to unify the specifications of various ORM frameworks in an official capacity, including the famous Hibernate, TopLink, etc. In this way, developers can avoid the need to learn an ORM framework in order to use Hibernate; in order to use the TopLink framework, they need to learn another ORM framework, eliminating the need to repeat the learning process!

3. Technologies covered by JPA

The overall idea of ​​JPA is roughly consistent with existing ORM frameworks such as Hibernate, TopLink, JDO, and Mybatis.

In general, JPA includes the following three technologies:

(1). ORM mapping metadata

JPA supports two forms of annotations in XML and JDK 5.0. Metadata describes the mapping relationship between objects and tables, and the framework persists entity objects into database tables accordingly.

(2).JPA API

It is used to operate entity objects and perform CRUD operations. The framework does all the work for us in the background, and developers are freed from cumbersome JDBC and SQL codes.

(3).Query language

Query data through object-oriented rather than database-oriented query language, avoiding the tight coupling of SQL statements of the program.

4. The relationship between JPA and other ORM frameworks

The essence of JPA is an ORM specification (not an ORM framework, because JPA does not provide an ORM implementation, but only a specification), not an implementation.

It only provides some related interfaces, but these interfaces cannot be used directly. The bottom layer of JPA needs some kind of JPA implementation, and frameworks such as Hibernate are a specific implementation of JPA.

也就是说JPA仅仅是一套规范,不是一套产品, Hibernate, TopLink等都是实现了JPA规范的一套产品。

Hibernate has been compatible with JPA since 3.2. Hibernate3.2 has obtained Sun TCK's JPA (Java Persistence API) compatible certification.

Therefore, the relationship between JPA and Hibernate can be simply understood as JPA is the standard interface, and Hibernate is the implementation. There is no benchmarking relationship between them. The following figure can show the relationship between them.

Hibernate is an implementation that follows the JPA specification, but Hibernate has other specifications to implement. So their relationship is more similar to: JPA is a standard specification for making noodles, and Hibernate is a specific noodle soup that follows the specification for making noodles; it not only follows the specification for making noodles, but also follows the specifications for making soup and seasoning other specifications.

5. Annotations in JPA

2. Spring Boot integrates JPA implementation process

1. Create a web application

According to our previous experience, we created a web program and transformed it into a Spring Boot project. The specific process is omitted.

2. Add dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>

3. Add configuration file

Create application.yml configuration file

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/db4?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
    type: com.alibaba.druid.pool.DruidDataSource
    username: root
    password: syc
    driver-class-name: com.mysql.jdbc.Driver #驱动
  jpa:
    hibernate:
      ddl-auto: update #自动更新
    show-sql: true  #日志中显示sql语句

jpa.hibernate.ddl-auto is the configuration property of hibernate. Its main function is to automatically create, update and verify the database table structure.

Several configurations of this parameter are as follows:

  • Create: Every time hibernate is loaded, the last generated table will be deleted, and then a new table will be regenerated according to your model class, even if there is no change twice, this is the one that leads to the loss of database table data important reason.
  • Create-drop: Every time hibernate is loaded, a table is generated according to the model class, but when the sessionFactory is closed, the table is automatically deleted.
  • update: The most commonly used attribute. When hibernate is loaded for the first time, the table structure will be automatically established according to the model class (the premise is that the database is established first). When hibernate is loaded later, the table structure will be automatically updated according to the model class, even if the table structure changes. But the rows in the table still exist without deleting the previous rows. It should be noted that when deployed to the server, the table structure will not be established immediately, it will not be established until the application is run for the first time.
  • Validate: Every time hibernate is loaded, the validation creates the database table structure, which will only be compared with the tables in the database. No new tables will be created, but new values ​​will be inserted.

4. Create entity class

package com.yyg.boot.domain;

import lombok.Data;
import lombok.ToString;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/3/30
 * @Description Description
 */
@Data
@ToString
@Entity
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String username;

    @Column
    private String birthday;

    @Column
    private String sex;

    @Column
    private String address;

}

5. Create a DataSource configuration class

package com.yyg.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/3/30
 * @Description 第二种配置数据源的方式
 */
@Data
@ComponentScan
@Configuration
@ConfigurationProperties(prefix="spring.datasource")
public class DbConfig {

    private String url;
    private String username;
    private String password;

    @Bean
    public DataSource getDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

}

6. Create a JPA entity repository

package com.yyg.boot.repository;

import com.yyg.boot.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/3/31
 * @Description Description
 */
public interface UserRepository extends JpaRepository<User, Long> {
}

7. Create a Controller test interface

package com.yyg.boot.web;

import com.yyg.boot.domain.User;
import com.yyg.boot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/3/31
 * @Description Description
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("")
    public List<User> findUsers() {
        return userRepository.findAll();
    }

   /**
     * 注意:记得添加@RequestBody注解,否则前端传递来的json数据无法被封装到User中!
     */
    @PostMapping("")
    public User addUser(@RequestBody User user) {
        return  userRepository.save(user);
    }

    @DeleteMapping(path = "/{id}")
    public String deleteById(@PathVariable("id") Long id) {
        userRepository.deleteById(id);
        return "success";
    }

}

8. Create Application startup class

package com.yyg.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @Author 一一哥Sun
 * @Date Created in 2020/3/31
 * @Description Description
 */
@SpringBootApplication
public class JpaApplication {

    public static void main(String[] args) {
        SpringApplication.run(JpaApplication.class, args);
    }

}

Complete project structure:

9. Test interface

Make a get query in the browser:

Perform the add operation in postman:

Perform delete operations in postman:

10. JPA implementation principle

JPA will generate SQL query statements based on the method name, which follows the principle of Convention over configuration (convention about configuration), and follows the method naming defined by Spring and JPQL. Spring provides a mechanism for query construction through naming rules. This mechanism first filters the method name by some keywords, such as find...By, read...By, query...By, count...By and get...By...

Then the system will parse the name into two sub-statements according to the keywords, and the first By is the keyword to distinguish the two sub-statements. The sub-statement before this By is a query sub-statement (indicates that the object to be queried is returned), and the following part is a conditional sub-statement.

If it is directly findBy... what is returned is the collection of domain objects specified when defining the Respository. At the same time, JPQL also defines rich keywords: and, or, Between, etc. Let's take a look at the keywords in JPQL:

Guess you like

Origin blog.csdn.net/dyuan134/article/details/130241720