Spring Boot 整合JDBC


今天主要讲解一下SpringBoot如何整合JDBC,没啥理论好说的,直接上代码,看项目整体结构

查看对应的pom.xml(父节点)

<?xml version="1.0" encoding="UTF-8"?>

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.6.RELEASE
         
    
    com.agan.boot
    agan-boot
    1.0.0-SNAPSHOT
    agan-boot
    Demo project for Spring Boot

    
        1.8
    

    

    

    
        agan-boot-config
        agan-boot-test1
        agan-boot-yml
        agan-boot-log
        agan-boot-test2
        agan-boot-jdbc
    
    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

查看对应的pom.xml(子节点)

<?xml version="1.0" encoding="UTF-8"?>

         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0
    
        com.agan.boot
        agan-boot
        1.0.0-SNAPSHOT
    
    com.agan.boot
    agan-boot-jdbc
    1.0.0-SNAPSHOT

    
        UTF-8
        UTF-8
        1.8
    

    

        
            org.springframework.boot
            spring-boot-starter-jdbc
        

        
            mysql
            mysql-connector-java
            5.1.36
            runtime
        

        
        
            com.alibaba
            druid
            1.1.5
        


       
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

定义User.java

package com.springboot.jdbc.bean;

import java.math.BigDecimal;

public class User {

    public User(Long id, String username) {
        super();
        this.id = id;
        this.username = username;
    }

    public User() {
        super();
    }

    private Long id;

    private String username;

    public Long getId() {
        return this.id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }


}

 定义数据源配置,这里使用druid,所以需要写一个配置类

package com.springboot.jdbc.config;

import java.sql.SQLException;
import javax.sql.DataSource;

import com.springboot.jdbc.resposity.UserDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
/**
 * @Function druid配置
 */
@Configuration
public class DruidConfig {
    private static  final Logger log = (Logger) LoggerFactory.getLogger(UserDAO.class);

    @Value("${spring.datasource.url}")
    private String dbUrl;

    @Value("${spring.datasource.username}")
    private String username;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.initialSize}")
    private int initialSize;

    @Value("${spring.datasource.minIdle}")
    private int minIdle;

    @Value("${spring.datasource.maxActive}")
    private int maxActive;

    @Value("${spring.datasource.maxWait}")
    private int maxWait;

    @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.minEvictableIdleTimeMillis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.validationQuery}")
    private String validationQuery;

    @Value("${spring.datasource.testWhileIdle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.testOnBorrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.testOnReturn}")
    private boolean testOnReturn;

    @Value("${spring.datasource.poolPreparedStatements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.filters}")
    private String filters;

    @Value("${spring.datasource.logSlowSql}")
    private String logSlowSql;

    @Bean
    @Primary //选择默认的数据源
    public DataSource dataSource(){
        //log.info("打桩 : 进入方法 dataSource ");

        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        datasource.setInitialSize(initialSize);
        datasource.setMinIdle(minIdle);
        datasource.setMaxActive(maxActive);
        datasource.setMaxWait(maxWait);
        datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
        datasource.setValidationQuery(validationQuery);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        //log.info("打桩 : *1*");
        try {
            //log.info("打桩 : *2*");
            datasource.setFilters(filters);
            //log.info("打桩 : *3*");
        } catch (SQLException e) {

            e.printStackTrace();
        }

        //log.info("打桩 : 退出方法 dataSource ");
        return datasource;
    }

    /**
     *
     * @return 添加登录权限
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean reg = new ServletRegistrationBean();
        reg.setServlet(new StatViewServlet());
        reg.addUrlMappings("/druid/*");
        reg.addInitParameter("loginUsername", username);
        reg.addInitParameter("loginPassword", password);
        reg.addInitParameter("logSlowSql", logSlowSql);
        return reg;
    }

    /**
     * 过滤规则
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        filterRegistrationBean.addInitParameter("profileEnable", "true");
        return filterRegistrationBean;
    }
}

上面指定druid的属性配置,和用户登录的账号信息以及对应的过滤规则:

下面定义数据访问接口和对应的实现:

package com.springboot.jdbc.resposity;


import com.springboot.jdbc.bean.User;

public interface IUserDAO {
    User findUserById(long id);
}
package com.springboot.jdbc.resposity;
import com.springboot.jdbc.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Repository
public class UserDAO implements IUserDAO {
    private static  final Logger log = (Logger) LoggerFactory.getLogger(UserDAO.class);
    /*public UserDAO(){
        log.info("打桩 : 进入UserDAO的无参构造方法。");
    }*/
    @Autowired
    private JdbcTemplate jdbcTemplate; // 这个是系统自带的
    @Override
    public User findUserById(long id) {

        //log.info("进入findUserById");
        List list = jdbcTemplate.query("select * from user where id = ?", new Object[]{id}, new BeanPropertyRowMapper(User.class));
        if(list!=null && list.size()>0){
            User account = list.get(0);
            return account;
        }else{
            return null;
        }

    }
}

数据访问层很简单,直接注入JdbcTemplate模板即可,下面再看对应的service和实现

package com.springboot.jdbc.service;


import com.springboot.jdbc.bean.User;

public interface IUserService {
    User findUser(long id);
}
package com.springboot.jdbc.service;


import com.springboot.jdbc.bean.User;
import com.springboot.jdbc.resposity.IUserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService implements IUserService {
    @Autowired
    private IUserDAO userDAO;
    @Override
    public User findUser(long id) {
        return userDAO.findUserById(id);
    }
}

写一个测试的controller:

package com.springboot.jdbc.controller;


import com.springboot.jdbc.bean.User;
import com.springboot.jdbc.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class UserController {
    @Autowired
    private IUserService userService;
    @GetMapping("/findUser/{id}")
    public User findUser(@PathVariable long id){
        return userService.findUser(id);
    }
}

对应的application.yaml配置文件

server:
  port: 8888

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat、wall、log4j    (踩过的坑,不能写成 )
    initialSize: 5
    maxActive: 20
    maxOpenPreparedStatements: 20
    maxWait: 60000
    minEvictableIdleTimeMillis: 300000
    minIdle: 1
    password: 123
    poolPreparedStatements: true
    testOnBorrow: false
    testOnReturn: false
    testWhileIdle: true
    timeBetweenEvictionRunsMillis: 60000
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:mysql://127.0.0.1:3306/emp
    username: root
    validationQuery: select 'x'
    logSlowSql: true
filters: stat、wall、log4j    (踩过的坑,不能写成 stat,wall,log4j , 用顿号,而不能用逗号

写一个启动应用类:

package com.springboot.jdbc;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class JdbcTemplateApplication {
    public static void main(String[] args) {
        SpringApplication.run(JdbcTemplateApplication.class,args);
    }
}

到此为止代码和配置文件都讲解完了,接下来进行创建数据库和数据表:

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  UNIQUE KEY `id_x` (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
 
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'jiahp');
INSERT INTO `user` VALUES ('2', 'wangli');
INSERT INTO `user` VALUES ('3', 'guoyanbin');
INSERT INTO `user` VALUES ('4', 'yaodong');

等应用成功启动成功之后,在浏览器端访问 http://localhost:8888/findUser/1 对应结果如下:

当然可以都访问几个id,然后再访问druid的监控页面 在浏览器端访问http://localhost:8888/druid/login.html

会弹出登录对话框,输入配置文件里面的用户名和密码就会登录成功,然后跳转到下面这样的页面

这上面的功能很多,比如sql监控:可以看到查询了哪些sql语句

还有url监控 可以查询对应sql调用的api:

还有其他功能,可以自己都点点看,还是蛮强大的,好了到此为止springboot和jdbc的整合就介绍完了

代码路径 : https://files.cnblogs.com/files/william-dai/agan-boot.rar 

参考文档: https://blog.csdn.net/qq_18603599/article/details/81169198