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(); }
|