(轉) Spring Boot JDBC 串連資料庫

來源:互聯網
上載者:User

標籤:

文本將對在Spring Boot構建的Web應用中,基於MYSQL資料庫的幾種資料庫連接方式進行介紹。 
包括JDBC、JPA、MyBatis、多資料來源和事務。

1 JDBC 串連資料庫1.1 屬性設定檔(application.properties)
spring.datasource.url=jdbc:mysql://localhost:3306/testspring.datasource.username=rootspring.datasource.password=123456spring.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日 */@Servicepublic 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: 1,name: "小明",sumScore: "252",avgScore: "84",age: 1},{id: 2,name: "小王",sumScore: "187",avgScore: "62.3",age: 1},{id: 3,name: "莉莉",sumScore: "",avgScore: "",age: 0},{id: 4,name: "柱子",sumScore: "230",avgScore: "76.7",age: 1},{id: 5,name: "大毛",sumScore: "",avgScore: "",age: 0},{id: 6,name: "亮子",sumScore: "0",avgScore: "0",age: 1}]

 

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/testspring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.max-idle=10spring.datasource.max-wait=10000spring.datasource.min-idle=5spring.datasource.initial-size=5spring.datasource.validation-query=SELECT 1spring.datasource.test-on-borrow=falsespring.datasource.test-while-idle=truespring.datasource.time-between-eviction-runs-millis=18800spring.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 串連資料庫

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.