前面两篇文章咱们介绍了如何快速建立一个 Spring Boot 工程 《Spring Boot(一):快速开始》和在 Spring Boot 中如何使用模版引擎 Thymeleaf 渲染一个Web页面 《Spring Boot (二):模版引擎 Thymeleaf 渲染 Web 页面》,本篇文章咱们继续介绍在 Spring Boot 中如何使用数据库。
数据库方面咱们选用 Mysql , Spring Boot 提供了直接使用 JDBC 的方式链接数据库,毕竟使用 JDBC 并非很方便,须要咱们本身写更多的代码才能使用,通常而言在 Spring Boot 中咱们经常使用的 ORM 框架有 JPA 和 Mybaties ,本篇文章咱们要介绍的就是 JPA 的使用姿式。html
说道使用 ORM 框架,就不得不顺便聊一下链接池,市面上不少成熟的数据库链接池,如 C3P0 、 Tomcat 链接池、 BoneCP 等等不少产品,可是咱们为何要介绍 Hikari ?这个要从 BoneCP 提及。java
由于,传说中 BoneCP 在快速这个特色上作到了极致,官方数据是C3P0等的25倍左右。不相信?其实我也不怎么信。但是,有图有真相啊,传说图片来源于官网,然而笔者在官网并无找到,你们看一下:mysql
看起来是否是彻底吊打,可是当 HikariCP 横空出世之后,这个局面就被彻底改写了, BoneCP 被 HikariCP 彻底吊打,看了一下 BoneCP Github 上面的版本更新,发如今2013年10月23日之后就再也没有更新过了,包括在仓库介绍上面都写着建议你们使用 HikariCP ,看来做者已经彻底心灰意冷了。git
Hikari 这个词来源于日文,是“光”的意思,估计做者的意思是这个链接池将会和光同样快,不知道做者是否是日本人。github
HikariCP 的口号是快速,简单,可靠。不知道是否真的如它本身宣传的同样,官方又提供了一张图,你们感觉一下,这张图来源于:https://github.com/brettwoold... 。web
更多有关 HikariCP 的信息,你们能够访问官方的 Github 仓库了解:https://github.com/brettwoold... ,笔者这里很少作介绍,毕竟咱们更关注的如何使用。spring
JPA (Java Persistence API) 是 Sun 官方提出的 Java 持久化规范。它为 Java 开发人员提供了一种对象/关联映射工具来管理 Java 应用中的关系数据。它的出现主要是为了简化现有的持久化开发工做和整合 ORM 技术,结束如今 Hibernate,TopLink,JDO 等 ORM 框架各自为营的局面。sql
值得注意的是,JPA 是在充分吸取了现有 Hibernate,TopLink,JDO 等 ORM 框架的基础上发展而来的,具备易于使用,伸缩性强等优势。从目前的开发社区的反应上看, JPA 受到了极大的支持和赞赏,其中就包括了 Spring 与 EJB3. 0的开发团队。数据库
注意: JPA 是一套规范,不是一套产品,那么像 Hibernate,TopLink,JDO 他们是一套产品,若是说这些产品实现了这个 JPA 规范,那么咱们就能够叫他们为 JPA 的实现产品。
Spring Boot JPA 是 Spring 基于 ORM 框架、 JPA 规范的基础上封装的一套 JPA 应用框架,可以使开发者用极简的代码便可实现对数据的访问和操做。它提供了包括增删改查等在内的经常使用功能,且易于扩展!学习并使用 Spring Data JPA 能够极大提升开发效率!apache
Spring Boot JPA 让咱们解脱了 DAO 层的操做,基本上全部 CRUD 均可以依赖于它来实现。
Spring Boot JPA 帮咱们定义了不少自定义的简单查询,而且能够根据方法名来自动生成 SQL ,主要的语法是 findXXBy
, readAXXBy
, queryXXBy
, countXXBy
, getXXBy
后面跟属性名称:
public interface UserRepository extends JpaRepository<UserModel, Long> { UserModel getByIdIs(Long id); UserModel findByNickName(String nickName); int countByAge(int age); List<UserModel> findByNickNameLike(String nickName); }
具体的关键字,使用方法和生产成SQL以下表所示:
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<Age> ages) | … where x.age in ?1 |
NotIn | findByAgeNotIn(Collection<Age> 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) |
这里咱们建立工程 spring-boot-jpa-hikari 。
代码清单: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>
代码清单: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
注意:
有关 JPA 的配置有一点须要的, spring.jpa.hibernate.ddl-auto
,这个属性需谨慎配置,它的几个值的含义对数据库来说都是高危操做,笔者这里方便起见配置了 update
,各位读者请根据具体使用场景配置。
com.zaxxer.hikari.HikariConfig
,笔者这里仅简单配置了自动提交、超时时间、最大最小链接数等配置。代码清单: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; }
代码清单: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); }
代码清单: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"; } }
测试咱们借助工具 PostMan ,启动工程,首先咱们新增一个用户信息,如图:
若是咱们参数中加入 id ,而且 id 的值和数据库中的 id 维持一致,这是会更新当前 id 的数据,如图:
咱们执行查询操做,如图:
执行删除操做,如图:
至此,测试完成。
https://github.com/brettwoold...
https://docs.spring.io/spring...
http://www.ityouknow.com/spri...