今天主要讲解一下SpringBoot如何整合JDBC,没啥理论好说的,直接上代码,看项目整体结构
看一下对应的pom.xml
4.0.0
spring_boot_jdbc
org.springframework.boot
spring-boot-starter-parent
1.5.2.RELEASE
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
定义User.java
package com.springboot.jdbc.bean;
import java.math.BigDecimal;
/**
* @Author 18011618
* @Date 9:49 2018/7/9
* @Function 用户信息
*/
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 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;
/**
* @Author 18011618
* @Date 17:19 2018/7/16
* @Function druid配置
*/
@Configuration
public class DruidConfig {
@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(){
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);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
e.printStackTrace();
}
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;
/**
* @Author 18011618
* @Description
* @Date 13:00 2018/7/13
* @Modify By
*/
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;
/**
* @Author 18011618
* @Description 使用JdbcTemplate模板
* @Date 13:09 2018/7/13
* @Modify By
*/
@Repository
public class UserDAO implements IUserDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public User findUserById(long id) {
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;
/**
* @Author 18011618
* @Description
* @Date 13:01 2018/7/13
* @Modify By
*/
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;
/**
* @Author 18011618
* @Description
* @Date 13:19 2018/7/13
* @Modify By
*/
@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;
/**
* @Author 18011618
* @Description
* @Date 13:00 2018/7/13
* @Modify By
*/
@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: 123123
poolPreparedStatements: true
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
timeBetweenEvictionRunsMillis: 60000
type: com.alibaba.druid.pool.DruidDataSource
url: jdbc:mysql://localhost:3306/emp
username: root
validationQuery: select 'x'
logSlowSql: true
写一个启动应用类:
package com.springboot.jdbc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @Author 18011618
* @Description
* @Date 13:22 2018/7/13
* @Modify By
*/
@SpringBootApplication
@EnableAutoConfiguration
public class JdbcTemplateApplication {
public static void main(String[] args) {
SpringApplication.run(JdbcTemplateApplication.class,args);
}
}
到此为止代码和配置文件都讲解完了,接下来进行创建数据库和数据表:
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- 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');
这里加了一个新注解:
@EnableAutoConfiguration:它是为了自动检查依赖的配置
等应用成功启动成功之后,在浏览器端访问 http://localhost:8888/findUser/1 对应结果如下:
当然可以都访问几个id,然后再访问druid的监控页面 在浏览器端访问 http://localhost:8888/druid/login.html
会弹出登录对话框,输入配置文件里面的用户名和密码就会登录成功,然后跳转到下面这样的页面
这上面的功能很多,比如sql监控:可以看到查询了哪些sql语句
还有url监控 可以查询对应sql调用的api:
还有其他功能,可以自己都点点看,还是蛮强大的,好了到此为止springboot和jdbc的整合就介绍完了..
版权声明:转载请标明博客地址,谢谢!