SpringBoot与数据库访问
JDBC
1、引入start
我们创建一个SpringBoot项目,引入jdbc以及mysql,在pom文件中可以看到引入的包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2、配置一个数据库连接
spring:
datasource:
username: root
data-password: 123456
url: jdbc:mysql://119.3.223.115:3306/jdbc
driver-class-name: com.mysql.cj.jdbc.Driver
3、编写一个测试类
@Autowired
DataSource dataSource;
@Test
public void contextLoads() throws SQLException {
//dataSource.getClass()class com.zaxxer.hikari.HikariDataSource
System.out.println("dataSource.getClass():"+dataSource.getClass());
Connection connection=dataSource.getConnection();
System.out.println("connection:"+connection);
connection.close();
}
效果:
默认是使用org.springframework.boot.autoconfigure.jdbc作为数据源:
数据源的相关配置都在DataSourceProperties里边
public class DataSourceProperties implements BeanClassLoaderAware, InitializingBean {
private ClassLoader classLoader;
private String name;
private boolean generateUniqueName;
private Class<? extends DataSource> type;
private String driverClassName;
private String url;
private String username;
private String password;
private String jndiName;
private DataSourceInitializationMode initializationMode;
private String platform;
private List<String> schema;
private String schemaUsername;
private String schemaPassword;
private List<String> data;
private String dataUsername;
private String dataPassword;
private boolean continueOnError;
private String separator;
private Charset sqlScriptEncoding;
private EmbeddedDatabaseConnection embeddedDatabaseConnection;
private DataSourceProperties.Xa xa;
private String uniqueName;
原理:
org.springframework.boot.autoconfigure.jdbc:
1、参考DataSourceConfiguration,根据配置床架的数据源,若没有规定spring.datasource.type的种类。则默认使用com.zaxxer.hikari.HikariDataSource的数据库连接池
2、目前2.1.8的springboot默认支持三类
【BasicDataSource(Dbcp2),HikariDataSource,org.apache.tomcat.jdbc.pool.DataSource】
3、或者我们可以自定义数据源
@Configuration
@ConditionalOnMissingBean({DataSource.class})
@ConditionalOnProperty(
name = {"spring.datasource.type"}
)
static class Generic {
Generic() {
}
@Bean
public DataSource dataSource(DataSourceProperties properties) {
//利用DataSourceBuilder创建数据源,利用反射创建响应type的数据源、并且绑定属性
return properties.initializeDataSourceBuilder().build();
}
}