Spring Boot (three): ORM JPA frame connection pooling Hikari

The previous two articles we described how to quickly create a Spring Boot project "Spring Boot (a): Quick Start" and how to use the template engine Thymeleaf render a Web page in Spring Boot in "Spring Boot (2): The template engine to render Web Thymeleaf page " , we continue this article describes how to use the database in Spring Boot.

1 Overview

Databases we use Mysql, Spring Boot provides a direct connection to the database using JDBC, after all, is not very convenient to use JDBC, we need to write more code to use, in general we often use ORM framework in the Spring Boot JPA and Mybaties, this article we want to introduce is the use of JPA posture.

He said use ORM framework, you have to talk about the way the connection pool, mature market, many database connection pool, such as C3P0, Tomcat connection pool, BoneCP so many products, but why should we introduce Hikari? This from BoneCP start.

Because, the legendary BoneCP achieve the ultimate in fast on this feature, official data about 25 times C3P0 like. Do not believe? In fact, I do not how the letter. However, there are pictures and the truth ah, the legendary image taken from the official website, but I did not find in the official website, look at:

Appears to be not completely easing the bit, but when HikariCP turned out, the situation was completely rewritten, BoneCP is HikariCP completely beating and hanging, looked BoneCP Github updated version of the above, it was found after October 23, 2013 have never been updated, including all written HikariCP suggest that you use in the warehouse introduced above, it appears that the author has completely disheartened.

The word comes from Japanese Hikari, "light" means, it is estimated the author means is this connection pool will be as fast and light, do not know the author is not Japanese.

HikariCP slogan is fast, simple and reliable. I do not know whether it is the same as its own propaganda, the official but also provides a map, we feel, this picture comes from: https: //github.com/brettwooldridge/HikariCP.

For more information about HikariCP, you can visit the official Github repository to understand: https: //github.com/brettwooldridge/HikariCP, I do not much introduced here, after all, we are more concerned about how to use.

2. JPA Introduction

JPA (Java Persistence API) is a Java Sun Crown persistence specification. It provides an object for Java developers / association mapping tools to manage relational data in Java applications. It appears mainly to simplify the existing persistence ORM technology development and integration, the end of the current Hibernate, TopLink, JDO and other ORM framework for their own business situation.

Notably, JPA is fully absorbed in the existing Hibernate, based TopLink, JDO and other ORM framework developed from, an easy to use, stretchable and strong advantages. From the reaction of the current development community point of view, JPA has been a great support and praise, including the Spring and EJB3. 0 of the development team.

Note: JPA is a specification, not a product, like Hibernate, TopLink, JDO they are a product, if these products achieve the JPA specification, then we can call them JPA implementations products.

JPA is based on the Boot Spring Spring Framework ORM, JPA specification package based on a JPA application framework, developers can use to achieve the minimalist code to access and manipulate data. It offers including CRUD etc., commonly used functions, and easy to expand! Learning and using Spring Data JPA can greatly improve development efficiency!

Spring Boot JPA let us relief operations DAO layer, basically all CRUD can rely on it to achieve.

Spring Boot JPA to help us define a number of custom queries simple, and can be automatically generated based on the method name SQL, the syntax is the main findXXBy, readAXXBy, queryXXBy, countXXBy, getXXByfollowed by property 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);
}

Specific keywords, and using production methods into SQL table below:

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. 工程实战

这里我们创建工程 spring-boot-jpa-hikari 。

3.1 工程依赖 pom.xml

代码清单: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连接驱动
  • spring-boot-starter-data-jpa:jpa相关的依赖包,这个包里包含了很多内容,包括我们使用的连接池 HikariCP ,从 Spring Boot 2.x 开始, Spring Boot 默认的连接池更换成为 HikariCP ,在当前的 Spring Boot 2.1.8 RELEASE 版本中,所使用的 HikariCP 版本为 3.2.0 ,如图:

3.2 配置文件 application.yml

代码清单: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&useUnicode=true&characterEncoding=UTF-8&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

注意:

  1. 有关 JPA 的配置有一点需要的, spring.jpa.hibernate.ddl-auto ,这个属性需谨慎配置,它的几个值的含义对数据库来讲都是高危操作,笔者这里方便起见配置了 update ,各位读者请根据具体使用场景配置。

    • create :每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。
    • create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。
    • update :最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等 应用第一次运行起来后才会。
    • validate :每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,但是会插入新值。
    • none :不做任何操作
  2. 有关 HikariCP 更多的配置可以参考源码类 com.zaxxer.hikari.HikariConfig ,笔者这里仅简单配置了自动提交、超时时间、最大最小连接数等配置。

3.3 映射实体类 UserModel.java

代码清单: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 : 唯一约束

  • 主键生成策略为uuid

3.4 资源类 UserRepository.java

代码清单: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 接口测试类 UserController.java

代码清单:spring-boot-jpa-hikari/src/main/java/com/springboot/springbootjpahikari/controller/UserController.java
***

@RestController
public class UserController {

    @Autowired
    UserRepository userRepository;

    /**
     * 查询用户列表
     * @return
     */
    @GetMapping("/user")
    public List<UserModel> user() {
        return userRepository.findAll(Sort.by("id").descending());
    }

    /**
     * 新增或更新用户信息
     * @param user
     * @return
     */
    @PostMapping("/user")
    public UserModel user(UserModel user) {
        return userRepository.save(user);
    }

    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/user")
    public String deleteUserById(Long id) {
        userRepository.deleteById(id);
        return "success";
    }
}

4. 测试

测试我们借助工具 PostMan ,启动工程,首先我们新增一个用户信息,如图:

如果我们参数中加入 id ,并且 id 的值和数据库中的 id 维持一致,这是会更新当前 id 的数据,如图:

我们执行查询操作,如图:

执行删除操作,如图:

至此,测试完成。

5. 示例代码

示例代码-Github

示例代码-Gitee

6. 参考

https://github.com/brettwooldridge/HikariCP

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/

http://www.ityouknow.com/springboot/2016/08/20/spring-boot-jpa.html

Guess you like

Origin www.cnblogs.com/babycomeon/p/11565843.html