Spring Boot 连接数据库
程序员文章站
2024-03-14 10:14:16
...
首先 Spring boot 有默认的一个连接池Hikari,这也就代表着,我们自己可以不用配置另外的连接池
InfoDaoImpl.class
@Repository
public class InfoDaoImpl {
@Autowired
private JdbcTemplate jdbcTemplate;
public Integer getAll(){
String sql = "select COUNT(*) from info";
Integer list = jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println(list);
return list;
}
}
application.properties(application.properties 是 springboot 在运行中所需要的配置信息)
spring.datasource.driVerclAssname=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=GMT
JdbcApplication.class
@SpringBootApplication
public class JdbcApplication {
public static void main(String[] args) {
ApplicationContext context =
SpringApplication.run(JdbcApplication.class, args);
context.getBean(InfoDaoImpl.class).getAll();
}
}
项目结构
所用依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
这样就可以调用Spring Boot默认的DataSource,如果想自己调用其他数据库的池,就得自己手动写配置,例如
InfoDaoImpl.class
和上面的InfoDaoImpl.class一样
JdbcApplication.class
和上面的JdbcApplication.class一样
DateSourceConfig.class
@Configuration
public class DateSourceConfig {
// 配置的阿里巴巴的连接池
@Bean
public DataSource dataSource(){
DataSource dataSource = new DruidDataSource();
((DruidDataSource) dataSource).setUrl("jdbc:mysql://localhost:3306/demo");
((DruidDataSource) dataSource).setDriverClassName("com.mysql.cj.jdbc.Driver");
((DruidDataSource) dataSource).setUsername("root");
((DruidDataSource) dataSource).setPassword("root");
return dataSource;
}
}
项目结构
所用依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<!-- 阿里巴巴连接池依赖 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
上一篇: ADO.NET连接数据库方法
下一篇: Mysql慢查询调优记录