Spring Boot: ORM framework JPA and connection pool Hikari

  1. For the database, we choose Mysql. Spring Boot provides a way to directly use JDBC to connect to the database. After all, using JDBC is not very convenient. We need to write more code ourselves to use it. Generally speaking, the ORM frameworks we commonly use in Spring Boot include JPA and Mybaties, what we want to introduce in this article is the usage posture of JPA.

When talking about using the ORM framework, we have to talk about connection pools. There are many mature database connection pools on the market, such as C3P0, Tomcat connection pool, BoneCP and many other products. But why should we introduce Hikari? This starts with BoneCP.

Because it is said that BoneCP has achieved the ultimate in speed, and the official data is about 25 times that of C3P0 and others. Do not believe? In fact, I don’t really believe it either. However, where there are pictures, there is truth. Legend has it that the pictures come from the official website, but I couldn’t find them on the official website. Let’s take a look:

It seems that it is completely defeated, but when HikariCP turned out, this situation was completely rewritten. BoneCP was completely defeated by HikariCP. After looking at the version updates on BoneCP Github, I found that after October 23, 2013 It has never been updated. Including the warehouse introduction, it is recommended that everyone use HikariCP. It seems that the author is completely frustrated.

The word Hikari comes from Japanese and means “light”. I guess the author means that this connection pool will be as fast as light. I don’t know if the author is Japanese.

HikariCP’s slogan is fast, simple and reliable. I don’t know if it is really as advertised, but the official provided another picture.

2. Introduction to JPA** (To understand the source code, please + request: 1791743380)**
JPA (Java Persistence API) is the Java persistence specification officially proposed by Sun. It provides Java developers with an object/relational mapping tool to manage relational data in Java applications. It emerged mainly to simplify existing persistence development work and integrate ORM technology, ending the current situation in which ORM frameworks such as Hibernate, TopLink, and JDO operate independently.

It is worth noting that JPA is developed on the basis of fully absorbing existing ORM frameworks such as Hibernate, TopLink, JDO, etc., and has the advantages of ease of use and strong scalability. Judging from the current reaction of the development community, JPA has received great support and praise, including the Spring and EJB3. 0 development teams.

Note: JPA is a set of specifications, not a set of products, so Hibernate, TopLink, and JDO are a set of products. If these products implement the JPA specification, then we can call them JPA implementation products.

Spring Boot JPA is a set of JPA application frameworks encapsulated by Spring based on the ORM framework and JPA specifications, which allows developers to access and operate data with minimalist code. It provides common functions including adding, deleting, modifying, checking, etc., and is easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency!

Spring Boot JPA frees us from the operation of the DAO layer, and basically all CRUD can be implemented relying on it.

Spring Boot JPA helps us define many custom simple queries, and can automatically generate SQL based on the method name. The main syntax is findXXBy, readAXXBy, queryXXBy, countXXBy, getXXBy followed by the attribute name:

public interface UserRepository extends JpaRepository<UserModel, Long> {
    UserModel getByIdIs(Long id);

    UserModel findByNickName(String nickName);

    int countByAge(int age);

    List<UserModel> findByNickNameLike(String nickName);
}

The specific keywords, usage methods and generated SQL are as 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 findByFirstname,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 like ?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 %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In 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)

3. Engineering practice
Here we create the project spring-boot-jpa-hikari.

3.1 Project dependency pom.xml
Code listing: spring-boot-jpa-hikari/pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springboot</groupId>
    <artifactId>spring-boot-jpa-hikari</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-jpa-hikari</name>
    <description>spring-boot-jpa-hikari</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

mysql-connector-java: mysql connection driver
spring-boot-starter-data-jpa: jpa-related dependency package, this package contains a lot of content, including the connection pool we use HikariCP. Starting from Spring Boot 2.x, Spring Boot’s default connection pool has been replaced by HikariCP. In the current Spring Boot 2.1.8 RELEASE version, the HikariCP version used is 3.2.0, as shown in the figure:

3.2 Configuration file application.yml
Code listing: spring-boot-jpa-hikari/src/main/resources/application.yml

server:
  port: 8080
spring:
  application:
    name: spring-boot-jpa-hikari
  jpa:
    database:mysql
    show-sql: true
    generate-ddl: true
    database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
    hibernate:
      ddl-auto: update
  datasource:
    url: jdbc:mysql://192.168.0.128:3306/test?serverTimezone=Asia/Shanghai & amp;useUnicode=true & amp;characterEncoding=UTF-8 & amp;useSSL=false
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      auto-commit: true
      minimum-idle: 2
      idle-timeout: 60000
      connection-timeout: 30000
      max-lifetime: 1800000
      pool-name: DatebookHikariCP
      maximum-pool-size: 5

Notice:

There is something needed about the configuration of JPA, spring.jpa.hibernate.ddl-auto. This property needs to be configured with caution. The meanings of its several values are high-risk operations for the database. The author has configured update here for convenience. Everyone Readers please configure according to specific usage scenarios.

create: Each time hibernate is loaded, the last generated table will be deleted, and then a new table will be generated based on your model class. This must be done even if there are no changes twice. This is an important reason for database table data loss. reason.
create-drop: The table is generated based on the model class every time hibernate is loaded, but the table is automatically deleted as soon as the sessionFactory is closed.
update: The most commonly used attribute. When hibernate is loaded for the first time, the table structure will be automatically established based on the model class (provided that the database is established first). When hibernate is loaded later, the table structure will be automatically updated based on the model class, even if the table structure changes. 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, but will wait until the application is run for the first time.
validate: Each time hibernate is loaded, it verifies the created database table structure. It will only compare it with the table in the database. No new table will be created, but new values will be inserted.
none: do nothing
For more configurations about HikariCP, please refer to the source code class com.zaxxer.hikari.HikariConfig. The author here only briefly configures automatic submission, timeout, maximum and minimum number of connections, etc.
3.3 Mapping entity class UserModel.java
Code listing: spring-boot-jpa-hikari/src/main/java/com/springboot/springbootjpahikari/model/UserModel.java

@Entity
@Data
@Table(name = "user")
public class UserModel {
    @Id
    @GeneratedValue(generator = "paymentableGenerator")
    @GenericGenerator(name = "paymentableGenerator", strategy = "uuid")
    @Column(name ="ID",nullable=false,length=36)
    private String id;
    @Column(nullable = true, unique = true)
    private String nickName;
    @Column(nullable = false)
    private int age;
}

unique: unique constraint

The primary key generation strategy is uuid

3.4 Resource class UserRepository.java
Code listing: spring-boot-jpa-hikari/src/main/java/com/springboot/springbootjpahikari/repository/UserRepository.java

public interface UserRepository extends JpaRepository<UserModel, Long> {
    UserModel getByIdIs(Long id);

    UserModel findByNickName(String nickName);

    int countByAge(int age);

    List<UserModel> findByNickNameLike(String nickName);
}

3.5 Interface test class UserController.java
Code listing: spring-boot-jpa-hikari/src/main/java/com/springboot/springbootjpahikari/controller/UserController.java

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    /**
     * Query user list
     * @return
     */
    @GetMapping("/user")
    public List<UserModel> user() {
        return userRepository.findAll(Sort.by("id").descending());
    }

    /**
     * Add or update user information
     * @param user
     * @return
     */
    @PostMapping("/user")
    public UserModel user(UserModel user) {
        return userRepository.save(user);
    }

    /**
     * Delete users based on id
     * @param id
     * @return
     */
    @DeleteMapping("/user")
    public String deleteUserById(Long id) {
        userRepository.deleteById(id);
        return "success";
    }
}

4. Test
To test, we use the tool PostMan to start the project. First, we add a new user information, as shown in the figure:


We perform query operations, as shown in the figure:

Perform the delete operation, as shown in the figure:

At this point, the test is completed.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 133681 people are learning the system