注册 X
我已阅读并同意  服务条款
首页 > IT技术笔记 > 查看笔记

springboot使用JdbcTemplate操作数据库

1、pom.xml文件加入mysql驱动依赖,数据库连接池以及jdbc依赖

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<scope>runtime</scope>

</dependency> 

<!--数据库连接池-->

     <dependency>

         <groupId>com.zaxxer</groupId>

         <artifactId>HikariCP</artifactId>

     </dependency>       

     <!--jdbc -->

        <dependency>

            <groupId>org.springframework.boot</groupId>

            <artifactId>spring-boot-starter-jdbc</artifactId>

        </dependency>

2、application配置文件增加数据库连接信息

20190729190448.png

3、增加JdbcConfig类和JdbcProperties类(代码在下面)

4、实例:

1120190729190815.png

点击复制

package com.rshare.datasource;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @author 这是一个jdbc配置类
 * prefix yml 里面的前缀 他会自动寻找位置并且赋值
 */
@ConfigurationProperties(prefix = "jdbc") 
public class JdbcProperties {
     private  String url;
     private String driverClassName;
     private String username;
     private String password;
 
     public String getUrl() {
          return url;
     }
 
     public void setUrl(String url) {
          this.url = url;
     }
 
     public String getDriverClassName() {
          return driverClassName;
     }
 
     public void setDriverClassName(String driverClassName) {
          this.driverClassName = driverClassName;
     }
 
     public String getUsername() {
          return username;
     }
 
     public void setUsername(String username) {
          this.username = username;
     }
 
     public String getPassword() {
          return password;
     }
 
     public void setPassword(String password) {
          this.password = password;
     }
}

package com.rshare.datasource;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
 
/**
 * @author 数据源配置类
 */
@Configuration
@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {
 
     @Bean
     public DataSource getDataSource(JdbcProperties jdbc){
          HikariDataSource dataSource = new HikariDataSource();
          dataSource.setJdbcUrl(jdbc.getUrl());
          dataSource.setDriverClassName(jdbc.getDriverClassName());
          dataSource.setUsername(jdbc.getUsername());
          dataSource.setPassword(jdbc.getPassword());
          return dataSource;
     }
}
			
		

 打赏        分享



评论