`

Spring Boot JDBC 连接数据库

阅读更多

 

JDBC 连接数据库

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
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

如果使用JNDI,则可以替代 spring.datasource 的 url、username、password,如:

spring.datasource.jndi-name=java:tomcat/datasources/example 
  • 1
  • 1

值得一提的是,无论是Spring Boot默认的DataSource配置还是你自己的DataSource bean,都会引用到外部属性文件中的属性配置。所以假设你自定义的DataSource bean,你可以在定义bean时设置属性,也可以在属性文件中,以“spring.datasource.*”的方式使属性配置外部化。

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

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;
            }

        });
    }
}
  • 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
  • 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

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 方法省略
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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();
    }
}
  • 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
  • 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

本文对工程添加文件后工程结构图: 
这里写图片描述

然后启动项目,访问地址: 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
}
]
  • 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
  • 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

连接池说明

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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

配置过连接池的开发人员对这些属性的意义都有所认识。

我们打开DEBUG日志输出,logback.xml 中添加:

<logger name="org.springframework.boot" level="DEBUG"/>
  • 1
  • 1

然后启动项目,注意观察日志输出,如下图中会显示自动启用了连接池: 
这里写图片描述 
我在上面的数据源配置中添加了过滤器,并设置了延迟时间为0(故意设置很低,实际项目中请修改):

spring.datasource.jdbc-interceptors=ConnectionState;SlowQueryReport(threshold=0)
  • 1
  • 1

这个时候,我们访问 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;
  • 1
  • 1
 
 

 

 

http://blog.csdn.net/catoop/article/details/50507516

分享到:
评论

相关推荐

    Spring boot连接oracle数据库JDBC配置步骤

    使用以上配置后,可以使用 Spring Boot 的测试工具来测试数据库连接是否正常。例如,可以使用 Spring Boot 的 `JdbcTemplate` 来执行一个简单的查询操作: ```java @RestController public class ...

    Spring Boot JDBC 连接数据库示例

    首先,我们需要在`application.properties`文件中配置数据库连接的相关属性。这些属性包括数据库URL、用户名、密码和驱动类名,例如: ```properties spring.datasource.url=jdbc:mysql://localhost:3306/test ...

    Spring Boot高级教程之Spring Boot连接MySql数据库

    接下来,新建Controller类测试数据库连接,使用@Autowired注入JdbcTemplate,使用@RequestMapping注解定义请求路径: package com.example.demo; import java.util.Iterator; import java.util.List; import java....

    spring-jdbc文件数据库配置加密

    Spring JDBC通过JdbcTemplate和NamedParameterJdbcTemplate等类,封装了数据库连接、SQL执行和结果集处理等复杂流程,降低了代码的冗余,提高了可读性和可维护性。在实际应用中,通常需要配置数据源(DataSource)来...

    Java spring boot链接mql数据库 JDBC

    接下来,配置Spring Boot的数据库连接。在`application.properties`或`application.yml`文件中添加如下配置: ```properties # application.properties 示例 spring.datasource.url=jdbc:mysql://localhost:3306/mr...

    Spring Boot连接MySQL数据库

    现在,Spring Boot会自动为`UserRepository`接口创建一个实现,并使用配置的数据库连接进行操作。在应用代码中,我们可以直接注入这个接口,然后调用其方法来执行查询、保存、删除等操作。 例如,要查找所有用户,...

    spring boot 达梦7数据库驱动包

    spring boot 达梦7数据库驱动包

    JAVA Spring boot JDBC同步不同服务器oracle数据库

    在Spring Boot的配置文件`application.properties`中,你需要设置两个服务器的Oracle数据库连接参数,如用户名、密码、URL等。例如: ``` spring.datasource.url=jdbc:oracle:thin:@server1:port1:servicename1 ...

    java中用spring boot连接oracle数据库代码下载

    以上就是在Spring Boot中连接Oracle数据库的基本步骤。通过这种方式,你可以轻松地实现数据库操作,同时享受到Spring Boot带来的便捷性。在实际开发中,还可以根据需求进一步优化,例如使用连接池、配置数据源的高级...

    spring-boot jdbc jsp Demo

    Spring Boot会自动识别这些配置并建立数据库连接。 然后,我们可以使用Spring的JdbcTemplate或NamedParameterJdbcTemplate来执行SQL查询。这些模板类封装了与数据库交互的细节,使得代码更简洁,同时保持了良好的...

    在IntelliJ IDEA中通过Spring Boot集成达梦数据库:从入门到精通

    3. **配置数据库连接** 在`application.properties`或`application.yml`文件中配置达梦数据库的连接信息,包括URL、用户名、密码等: ```properties spring.datasource.url=jdbc:dm://localhost:5236/your_...

    spring boot jdbc的sql文例子

    如果使用的是内嵌数据库(如H2或HSQL),只需在`application.properties`或`application.yml`文件中设置相关的数据库连接信息,例如: ```properties spring.datasource.url=jdbc:h2:mem:testdb spring.datasource....

    Spring Boot 系列教程 JDBC

    【Spring Boot 系列教程 JDBC】是一套针对Java开发者深入学习Spring Boot集成JDBC技术的教程。本教程旨在帮助开发者理解和应用Spring Boot框架中的JDBC功能,以简化数据库操作,提高开发效率。JDBC(Java Database ...

    spring boot连接数据库(jpa)

    总结,通过Spring Boot、JPA和Hibernate,我们可以轻松地连接和操作MySQL数据库。配置好YML文件后,利用Spring Data JPA的便捷功能,我们可以快速实现数据的CRUD操作,极大地提高了开发效率。在实际项目中,还可以...

    boot-crmSpring数据库开发--SpringJDBC的配置

    在Spring框架中,Spring JDBC是连接数据库的重要模块,它提供了对JDBC的抽象层,使得开发者可以更加方便、高效地进行数据库操作。本教程将详细讲解如何在Spring Boot项目中配置Spring JDBC,以便进行数据库开发。 ...

    Spring Boot 配置MySQL数据库重连的操作方法

    在使用 Spring Boot 时,配置 MySQL 数据库连接是一个非常重要的步骤。然而,在实际应用中,我们可能会遇到连接超时、连接失效等问题,导致应用程序无法连接到 MySQL 数据库。因此,本文将主要介绍 Spring Boot 配置...

    spring boot做的显示数据库的数据

    总的来说,这个项目涵盖了Spring Boot的基本应用、数据库连接配置、JPA实体映射、Repository接口使用以及控制器方法的实现,这些都是开发基于Spring Boot和MySQL应用的基础。通过这个实践,开发者可以深入理解Spring...

    Spring Data JDBC与JDBC的区别

    JDBC规范   java.sql和javax.sql两个包中的类与接口(天龙八部):  DataSource:数据源  DriverManager:驱动管理  Driver:JDBC驱动 ... JDBC数据库连接池/Connection Pool  DBCP:apache tomcat内置  

    spring boot资料以及项目

    Spring Boot对于数据库的支持非常全面,包括JDBC、MyBatis、Hibernate等,资料中可能有相关的数据库集成示例。它还内置了Spring Data JPA,提供了方便的数据访问层抽象。此外,Spring Boot还集成了Thymeleaf、...

    [课堂课件讲解]Java微服务实践-Spring Boot 数据库JDBC.pptx

    数据源是数据库连接的来源,通过DataSource接口获取。有三种类型的数据源: 1. 通用型数据源(javax.sql.DataSource):主要用于通用型数据库,本地事务,一般通过Socket方式连接。 2. 分布式数据源(javax.sql....

Global site tag (gtag.js) - Google Analytics