JDBC
JDBC
是一套执行SQL
语句的API
,它提供了一种基准,Java
连接数据库必须遵循这个基准,数据库厂商负责提供JDBC
驱动程序,由驱动程序建立程序和数据库之间的连接
JDBC配置
传统的配置方式
1 2 3 4 5 6
| <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency>
|
新版本的MySQL
连接器的配置方式
1 2 3 4 5 6
| <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> <version>9.2.0</version> </dependency>
|
加载驱动
传统的MySQL jdbc
驱动程序加载方式
1 2 3 4 5 6
| Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
|
如下方式加载驱动程序,线程安全性更高,此外通过DataSource
接口实现的类可以更好地与连接池集成,便于管理和优化连接
1 2 3 4 5 6 7 8 9 10
| Class.forName("com.mysql.cj.jdbc.Driver");
MysqlDataSource dataSource = new MysqlDataSource(); dataSource.setUrl(url); dataSource.setUser(username); dataSource.setPassword(password); Connection connection = dataSource.getConnection();
Statement statement = connection.createStatement();
|
执行命令
执行增、删、改命令,返回被影响的行数
1
| int result = statement.executeUpdate(sql);
|
执行查询命令,返回结果集
1 2 3 4 5 6 7 8 9 10 11 12 13
| ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) { String softName = resultSet.getString("softName"); float softSize = resultSet.getFloat("softSize"); System.out.println("softName: " + softName + ", softSize: " + softSize); }
resultSet.close(); statement.close(); connection.close();
|
Mybatis
MyBatis Spring Boot Starter
是Spring Boot
官方提供的MyBatis
集成方案,简化了MyBatis
与Spring Boot
的集成过程
1 2 3 4 5 6
| <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.4</version> </dependency>
|
配置Mybatis
配置,在application.properties
中配置Mybatis
的相关信息
1 2 3 4 5 6 7
| spring.datasource.url=jdbc:mysql://localhost:3306/db
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root spring.datasource.password=admin
|
根据数据库表,创建对应的实体类,Mybatis
会自动把查询到的数据,根据数据库表的字段名,映射到实体类对应的属性上
1 2 3 4
| CREATE TABLE soft( softName VARCHAR(20), softSize FLOAT );
|
1 2 3 4 5 6
| @Data @NoArgsConstructor public class Soft { private String softName; private float softSize; }
|
编写Mybatis
的持久层接口,通过@Mapper
给接口添加注解,Mybatis
会自动扫描注解@Mapper
的接口,动态的为该接口生成一个实现类,并将该实现类对象注入到Spring
的IOC
容器中
通过@Select
注解,Mybatis
会自动执行注解中的SQL
语句,并把查询结果集映射到实体类对应的属性上,结果集中多个实体类组成集合并返回
1 2 3 4 5
| @Mapper public interface SoftMapper { @Select("SELECT * FROM soft") List<Soft> select(); }
|