【Spring Boot 九】 JDBC 连接数据库
文本将对在spring Boot构建的Web应用中,基于MySQL数据库的几种数据库连接方式进行介绍。
包括JDBC、JPA、MyBatis、多数据源和事务。
JDBC 连接数据库
1、属性配置文件(/src/main/resources/application.properties)
1 2 3 4 |
spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver |
值得一提的是,无论是Spring Boot默认的DataSource配置还是你自己的DataSource bean,都会引用到外部属性文件中的属性配置。所以假设你自定义的DataSource bean,你可以在定义bean时设置属性,也可以在属性文件中,以“spring.datasource.*”的方式使属性配置外部化。
2、pom.xml 配置maven依赖
1 2 3 4 5 6 7 8 9 10 11 12 |
<!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.42</version> </dependency> <!-- Spring Boot JDBC --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> |
下面看一下我的controller,我在controller直接调用数据库了,当然,这是不妥当的做法,我在这里只是做一下演示,正确的编码行为应该是controller->service->dao。
OrderController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.spring.boot.controller; import com.spring.boot.entity.Order; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.List; /** * OrderController * Created by XJH on 2017/8/25. */ @RestController @RequestMapping("/order") public class OrderController { private final Logger log = LoggerFactory.getLogger(this.getClass()); private final JdbcTemplate jdbcTemplate; @Autowired public OrderController(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @RequestMapping(value = "/list", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"}) public List<Order> getList() { log.info("invoke----------/order/list.GET"); String sql = "SELECT id, type, resource_id, state, create_time, user_id, credits, amount, update_time FROM `order`"; return jdbcTemplate.query(sql, (rs, rowNum) -> { Order order = new Order(); order.setId(rs.getInt("ID")); order.setAmount(rs.getDouble("AMOUNT")); order.setType(rs.getString("TYPE")); order.setCreateTime(rs.getDate("CREATE_TIME")); order.setUpdateTime(rs.getDate("UPDATE_TIME")); order.setCredits(rs.getDouble("CREDITS")); order.setResourceId(rs.getInt("RESOURCE_ID")); order.setState(rs.getString("STATE")); order.setUserId(rs.getInt("USER_ID")); return order; }); } } |
Order.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.spring.boot.entity; import java.io.Serializable; import java.util.Date; /** * Order * Created by XJH on 2017/8/25. */ public class Order implements Serializable { private Integer id; //自增主键id private String type; //类型 private Integer resourceId; //资源id private String state; //状态 private Date createTime; //创建时间 private Date updateTime; //更新时间 private Integer userId; //userid private Double credits; //积分 private Double amount; //金额 //为了篇幅,此处setter()和getter()方法省略 } |
在数据库的test数据库order表中添加几条测试数据进行测试
运行SpringBootSampleApplication启动项目,
访问:http://localhost:8080/order/list
结果:
[{"id":1,"type":"asd","resourceId":1,"state":"asd","createTime":"2017-08-25","updateTime":"2017-08-25","userId":1,"credits":10.0,"amount":20.0},{"id":2,"type":"bb","resourceId":2,"state":"asd","createTime":"2017-08-25","updateTime":"2017-08-25","userId":2,"credits":30.0,"amount":40.0}]
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 依赖。
假如我们想用其他方式的连接池技术(阿里druid、c3p0、dbcp等),只要配置自己的DataSource bean,即可覆盖Spring Boot的自动配置。
请看我的数据源配置(/src/main/resources/application.properties):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#数据库连接信息 spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root 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) |
虽然实际开发中jdbc用的不太多,一般都用ORM框架,比如mybatis、Hibernate(相对较少),但是jdbc毋庸置疑是最快的,因为基于底层,所以效率最高,所以还是有学习的必要的!
今朝又七夕
情人节快乐
相爱且不易
且行且珍惜
发表评论