本文介绍 Spring Boot 2 集成 MariaDB Connector/J 驱动连接 MySQL 数据库的方法。
目录
MariaDB Connector/J 简介
版本说明
代码示例
MariaDB Connector/J 简介
MariaDB 是一个开源关系型数据库,由 MySQL 的一些原始开发者领导,与 MySQL 保持高度兼容。
尽管 MySQL 官方提供了 MySQL Connector/J 驱动,但是因为使用了 GPL V2.0 协议,导致所有引用此驱动的软件都不得不开源,MariaDB Connector/J 驱动使用的是 LGPL V2.1 开源协议,对商业应用更加友好,因此可以使用 MariaDB Connector/J 替代 MySQL Connector/J 用于连接 MySQL 数据库。
版本说明
JDK 8
MySQL 8.x
MariaDB Connector/J 2.6.0
代码示例
创建存储用户信息的数据表。
CREATE TABLE `user` (
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(16) NOT NULL COMMENT '姓名',
`age` INT UNSIGNED NOT NULL COMMENT '年龄',
`email` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '电子邮箱',
PRIMARY KEY (`id`),
UNIQUE INDEX `uk_name` (`name` ASC)
) COMMENT='用户信息';
在生成的 pom 文件中添加 spring-boot-starter-jdbc 和 mariadb-java-client 依赖。
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.7.RELEASE
tutorial.spring.boot
spring-boot-mysql-mariadb-driver
0.0.1-SNAPSHOT
spring-boot-mysql-mariadb-driver
1.8
org.springframework.boot
spring-boot-starter-jdbc
org.mariadb.jdbc
mariadb-java-client
2.6.0
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
org.springframework.boot
spring-boot-maven-plugin
在 application.yml 中添加数据源配置。
spring:
datasource:
driver-class-name: org.mariadb.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false
编写映射数据表的领域模型类。
package tutorial.spring.boot.mysql.domain;
import java.util.Objects;
public class User {
/**
* 数据库表 user 列名
*/
public static class ColumnConstant {
public static final String ID = "id";
public static final String NAME = "name";
public static final String AGE = "age";
public static final String EMAIL = "email";
}
private Long id;
private String name;
private Integer age;
private String email;
public User(String name, Integer age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getter and Setter 略
@Override
public boolean equals(Object o) {
if (this =&#