(转) Spring Boot JDBC 连接数据库
文本将对在Spring Boot构建的Web应用中,基于MYSQL数据库的几种数据库连接方式进行介绍。
包括JDBC、JPA、MyBatis、多数据源和事务。
1 JDBC 连接数据库
1.1 属性配置文件(application.properties)
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
如果使用JNDI,则可以替代 spring.datasource 的 url、username、password,如:(不理解)
spring.datasource.jndi-name=java:tomcat/datasources/example
值得一提的是,无论是Spring Boot默认的DataSource配置还是你自己的DataSource bean,都会引用到外部属性文件中的属性配置。所以假设你自定义的DataSource bean,你可以在定义bean时设置属性,也可以在属性文件中,以“spring.datasource.*”的方式使属性配置外部化。
1.2 pom.xml 配置maven依赖
<!-- MYSQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Spring Boot JDBC -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
1.3 Java代码范例
StudentService.java
package org.springboot.sample.service; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import org.springboot.sample.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; /**
* Studeng Service
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年1月12日
*/
@Service
public class StudentService { @Autowired
private JdbcTemplate jdbcTemplate; public List<Student> getList(){
String sql = "SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE FROM STUDENT";
return (List<Student>) jdbcTemplate.query(sql, new RowMapper<Student>(){ @Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
Student stu = new Student();
stu.setId(rs.getInt("ID"));
stu.setAge(rs.getInt("AGE"));
stu.setName(rs.getString("NAME"));
stu.setSumScore(rs.getString("SCORE_SUM"));
stu.setAvgScore(rs.getString("SCORE_AVG"));
return stu;
} });
}
}
Student.java 实体类
package org.springboot.sample.entity; import java.io.Serializable; /**
* 学生实体
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年1月12日
*/
public class Student implements Serializable{ private static final long serialVersionUID = 2120869894112984147L; private int id;
private String name;
private String sumScore;
private String avgScore;
private int age; // 节省文章长度,get set 方法省略
}
StudentController.java
package org.springboot.sample.controller; import java.util.List; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springboot.sample.entity.Student;
import org.springboot.sample.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@RequestMapping("/stu")
public class StudentController { private static final Logger logger = LoggerFactory.getLogger(StudentController.class); @Autowired
private StudentService studentService; @RequestMapping("/list")
public List<Student> getStus(){
logger.info("从数据库读取Student集合");
return studentService.getList();
}
}
本文对工程添加文件后工程结构图:
然后启动项目,访问地址: http://localhost:8080/myspringboot/stu/list 响应结果如下:
[
{
id: ,
name: "小明",
sumScore: "252",
avgScore: "84",
age:
},
{
id: ,
name: "小王",
sumScore: "187",
avgScore: "62.3",
age:
},
{
id: ,
name: "莉莉",
sumScore: "",
avgScore: "",
age:
},
{
id: ,
name: "柱子",
sumScore: "230",
avgScore: "76.7",
age:
},
{
id: ,
name: "大毛",
sumScore: "",
avgScore: "",
age:
},
{
id: ,
name: "亮子",
sumScore: "0",
avgScore: "0",
age:
}
]
2 连接池说明
Tomcat7之前,Tomcat本质应用了DBCP连接池技术来实现的JDBC数据源,但在Tomcat7之后,Tomcat提供了新的JDBC连接池方案,作为DBCP的替换或备选方案,解决了许多之前使用DBCP的不利之处,并提高了性能。详细请参考:http://wiki.jikexueyuan.com/project/tomcat/tomcat-jdbc-pool.html
Spring Boot为我们准备了最佳的数据库连接池方案,只需要在属性文件(例如application.properties)中配置需要的连接池参数即可。
我们使用Tomcat数据源连接池,需要依赖tomcat-jdbc,只要应用中添加了spring-boot-starter-jdbc 或 spring-boot-starter-data-jpa依赖,则无需担心这点,因为将会自动添加 tomcat-jdbc 依赖。
假如我们想用其他方式的连接池技术,只要配置自己的DataSource bean,即可覆盖Spring Boot的自动配置。
请看我的数据源配置:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-idle=10
spring.datasource.max-wait=10000
spring.datasource.min-idle=5
spring.datasource.initial-size=5
spring.datasource.validation-query=SELECT 1
spring.datasource.test-on-borrow=false
spring.datasource.test-while-idle=true
spring.datasource.time-between-eviction-runs-millis=18800
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
配置过连接池的开发人员对这些属性的意义都有所认识。
我们打开DEBUG日志输出,logback.xml 中添加:
<logger name="org.springframework.boot" level="DEBUG"/>
然后启动项目,注意观察日志输出,如下图中会显示自动启用了连接池:
我在上面的数据源配置中添加了过滤器,并设置了延迟时间为0(故意设置很低,实际项目中请修改):
spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
这个时候,我们访问 http://localhost:8080/myspringboot/stu/list 观察日志,会发现框架自动将大于该时间的数据查询进行警告输出,如下:
2016-01-12 23:27:06.710 WARN 17644 --- [nio-8080-exec-1] o.a.t.j.p.interceptor.SlowQueryReport : Slow Query Report SQL=SELECT ID,NAME,SCORE_SUM,SCORE_AVG, AGE FROM STUDENT; time=3 ms;
(转) Spring Boot JDBC 连接数据库的更多相关文章
- Spring Boot JDBC 连接数据库
文本将对在Spring Boot构建的Web应用中,基于MYSQL数据库的几种数据库连接方式进行介绍. 包括JDBC.JPA.MyBatis.多数据源和事务. JDBC 连接数据库 1.属性配置文件( ...
- 10. Spring Boot JDBC 连接数据库
转自:https://blog.csdn.net/catoop/article/details/50507516
- (转) Spring Boot MyBatis 连接数据库
最近比较忙,没来得及抽时间把MyBatis的集成发出来,其实mybatis官网在2015年11月底就已经发布了对SpringBoot集成的Release版本,Github上有代码:https://gi ...
- spring boot中连接数据库报错500(mybatis)
spring boot中连接数据库报错500(mybatis) pom.xml中的依赖 <!-- 集成mybatis--> <dependency> <groupId&g ...
- Spring Boot MyBatis 连接数据库
最近比较忙,没来得及抽时间把MyBatis的集成发出来,其实mybatis官网在2015年11月底就已经发布了对SpringBoot集成的Release版本,Github上有代码:https://gi ...
- Spring Boot JPA 连接数据库
本文将介绍怎样在Spring Boot project中加入JPA作为持久化方式. 改动 pom.xml 依赖 与上一篇介绍的 jdbc 不同的是 spring-boot-starter-jdbc 改 ...
- spring boot 不连接数据库启动
Consider the following: If you want an embedded database (H2, HSQL or Derby), please put it on th ...
- Spring boot + jdbc学习笔记
pom.xml: <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www. ...
- Spring Boot JDBC:加载DataSource过程的源码分析及yml中DataSource的配置
装载至:https://www.cnblogs.com/storml/p/8611388.html Spring Boot实现了自动加载DataSource及相关配置.当然,使用时加上@EnableA ...
随机推荐
- 搭建rtmp直播流服务之3:java开发ffmpeg实现rtsp转rtmp并实现ffmpeg命令的接口化管理架构设计及代码实现
上一篇文章简单介绍了java如何调用ffmpeg的命令:http://blog.csdn.net/eguid_1/article/details/51777716 上上一篇介绍了nginx-rtmp服 ...
- Spring+SpringMVC+MyBatis深入学习及搭建(十二)——SpringMVC入门程序(一)
转载请注明出处:http://www.cnblogs.com/Joanna-Yan/p/6999743.html 前面讲到:Spring+SpringMVC+MyBatis深入学习及搭建(十一)——S ...
- ios开发 oc 的类方法与对象方法
--------开始前先申明一下:小编为了让大家看出效果,在编码中命名方式会又些不规范. 首先我们先来了解一下什么是类方法与对象方法. 对象方法: 对象是由“-”开头.比如:-(void)Runner ...
- scrapy中的下载器中间件
scrapy中的下载器中间件 下载中间件 下载器中间件是介于Scrapy的request/response处理的钩子框架. 是用于全局修改Scrapy request和response的一个轻量.底层 ...
- win7安装oracle10g数据库 提示“…实际版本为6.1”
1.最重要的是需要以管理员的身份操作 2.修改重要的文件 然后解压,在目录中找到refhost.xml(有两个,我的一个是在stage\prereq\db目录下,一个是在stage\prereq\db ...
- ClistCtrl用法及总结(由怎样隐藏ListCtrl列表头的排序小三角形这个bug学习到的知识)
1 怎样隐藏ListCtrl列表头的排序小三角形 在创建控件是加入|LVS_NOSORTHEADER风格即可. 一下是用法总结: 本文根据本人在项目中的应用,来谈谈CListCtrl的部分用法及技巧. ...
- javascript所有的节点和方法
属性: 1.Attributes 存储节点的属性列表(只读) 2.childNodes 存储节点的子节点列表(只读) 3.dataType 返回此节点的数据类型 4.Definition 以DTD或X ...
- linux下安装QT5:error: unrecognized command line option ‘-fuse-ld=gold’
安装qt时在执行./configure时报错:error: unrecognized command line option '-fuse-ld=gold' 这个错误是qt的一个bug. 在装有gol ...
- iOS基于AVPlayer的视频播放
基于 AVPlayer 自定义播放器http://www.cocoachina.com/ios/20160921/17609.html,http://www.2cto.com/kf/201608/53 ...
- 使用dns批量管理普通主机名相关问题
1.dns配置 日常管理主机过程中,会有很多地方需要使用到主机名的,当主机非常多的时候,就不适合使用hosts来管理和同步的所有主机hosts了,这个时候就可以使用dns来管理主机名映射和变动 dns ...