springboot【8】数据访问之JdbcTemplate访问数据库

来源:互联网 发布:淘宝店铺logo分辨率 编辑:程序博客网 时间:2024/06/05 01:13


一、数据源配置

在我们访问数据库的时候,需要先配置一个数据源,下面分别介绍一下几种不同的数据库配置方式。

首先,为了连接数据库需要引入jdbc支持,在pom.xml中引入如下配置:

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jdbc</artifactId></dependency>

嵌入式数据库支持

嵌入式数据库通常用于开发和测试环境,不推荐用于生产环境。Spring Boot提供自动配置的嵌入式数据库有H2、HSQL、Derby,不需要提供任何连接配置就能使用。

比如,我们可以在pom.xml中引入如下配置使用HSQL。

<dependency>    <groupId>org.hsqldb</groupId>    <artifactId>hsqldb</artifactId>    <scope>runtime</scope></dependency>

连接生产数据源

以MySql数据库为例,先引入MySql连接的依赖包,在pom.xml中加入:

<dependency>    <groupId>mysql</groupId>    <artifactId>mysql-connector-java</artifactId>    <version>5.1.21</version></dependency>

src/main/resources/application.properties中配置数据源信息

spring.datasource.url=jdbc:mysql://localhost:3306/springbootspring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver

连接JNDI数据源

将应用部署到应用服务器上的时候想让数据源由应用服务器管理,那么可以使用如下配置方式引入JNDI数据源。

spring.datasource.jndi-name=java:jboss/datasources/customers


二、使用JdbcTemplate操作数据库

Spring的JdbcTemplate是自动配置的,可以直接使用@Autowired来注入到自己的bean中来使用。

举例:我们创建User表,包含属性nameage,下面来编写数据访问对象和单元测试用例。

  • 定义包含有插入、删除、查询的抽象接口UserService
package com.lyd.service;/** *  * <p>Title: UserService.java</p> * <p>Description: 用户管理接口</p> * @author lyd * @date 2017年8月2日 * @version 1.0 * @blog springboot学习http://blog.csdn.net/IT_lyd/article/category/6692929 */public interface UserService {    /**     * 新增一个用户     * @param name     * @param age     */    void create(String name, Integer age);    /**     * 根据name删除一个用户高     * @param name     */    void deleteByName(String name);    /**     * 获取用户总量     */    Integer getAllUsers();    /**     * 删除所有用户     */    void deleteAllUsers();}
  • 通过JdbcTemplate实现UserService中定义的数据访问操作
package com.lyd.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.stereotype.Service;@Servicepublic class UserServiceImpl implements UserService{@Autowiredprivate JdbcTemplate jdbcTemplate;@Overridepublic void create(String name, Integer age) {jdbcTemplate.update("INSERT INTO USER(NAME, AGE) VALUES(?, ?)", name, age);}@Overridepublic void deleteByName(String name) {jdbcTemplate.update("DELETE FROM USER WHERE NAME = ?", name);}@Overridepublic Integer getAllUsers() {return jdbcTemplate.queryForObject("SELECT COUNT(1) FROM USER", Integer.class);}@Overridepublic void deleteAllUsers() {jdbcTemplate.update("DELETE FROM USER");}}
  • 创建对UserService的单元测试用例,通过创建、删除和查询来验证数据库操作的正确性。
package com.lyd;import org.junit.Assert;import org.junit.Before;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.SpringApplicationConfiguration;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import com.lyd.service.UserService;@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Application.class)public class ApplicationTest {@Autowiredprivate UserService userService;@Beforepublic void setUp(){// 准备,清空user表userService.deleteAllUsers();}@Testpublic void test(){// 插入5个用户userService.create("a", 1);userService.create("b", 2);userService.create("c", 3);userService.create("d", 4);userService.create("e", 5);// 查数据库,应该有5个用户Assert.assertEquals(5, userService.getAllUsers().intValue());// 删除两个用户userService.deleteByName("a");userService.deleteByName("e");// 再次查数据库,应该有3个用户Assert.assertEquals(3, userService.getAllUsers().intValue());}}

上面介绍的JdbcTemplate只是最基本的几个操作,更多其他数据访问操作的使用请参考:JdbcTemplate API

通过上面这个简单的例子,我们可以看到在Spring Boot下访问数据库的配置依然秉承了框架的初衷:简单。我们只需要在pom.xml中加入数据库依赖,再到application.properties中配置连接信息,不需要像Spring应用中创建JdbcTemplate的Bean,就可以直接在自己的对象中注入使用。



三、关于pom.xml的补充说明

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jdbc</artifactId></dependency>

通过这个模块为我们做了以下几件事

  • tomcat-jdbc-{version}.jar为我们自动配置DataSource.

  • 如果你没有定义任何DataSource,SpringBoot将会自动配置一个内存的数据库资源设置

  • 如果没有设置任一个beans,SpringBoot会自动注册它

  • 初始化数据库

    如果我们在classpath里定义了schema.sql和data.sql文件,springBoot将会使用这些文件自动初始化数据库(但你必须选建库)除了载入schema.sql和data.sql外,SpringBoot也会载入schema-${platform}.sql和data-${platform}.sql,如果在你的classpath下存在的话。
    spring.datasource.schema=xxxx-db.sql 可以定义你的建库文件spring.datasource.data=xxxx-data.sql  可以定义你的数据文件spring.datasource.initialize=true|false 可以决定是不是要初始化这些数据库文件spring.datasource.continueOnError=true|false 有了错误是否继续运行

定义数据库驱动信息

/src/main/resources/application.yml

logging:  level:    org.springframework: INFO    com.example: DEBUG################### DataSource Configuration ##########################spring:  datasource:    driver-class-name: com.mysql.jdbc.Driver    url: jdbc:mysql://localhost:3306/gs-jdbc    username: root    password:    initialize: trueinit-db: true

其中

spring:  datasource:    driver-class-name: com.mysql.jdbc.Driver    url: jdbc:mysql://localhost:3306/gs-jdbc    username: root    password:

我是用的mysql,你也可以定义其它或者不定义,如果不定义,springBoot会自动为我们配置一个嵌入的数据库( Embedded database)


自定义数据源

如果你不想用默认的配置数据源,如你想用阿里巴巴的数据池管理数据源,你也可以自己配置

先排除tomcat-jdbc的默认配置dataSource

<dependency>    <groupId>org.springframework.boot</groupId>    <artifactId>spring-boot-starter-jdbc</artifactId>    <exclusions>        <exclusion>            <groupId>org.apache.tomcat</groupId>            <artifactId>tomcat-jdbc</artifactId>        </exclusion>    </exclusions></dependency>

定义自己的数据资源 这里使用了阿里巴巴的数据池管理,你也可以使用BasicDataSource

<dependency>    <groupId>com.alibaba</groupId>    <artifactId>druid</artifactId>    <version>1.0.19</version></dependency>
/src/main/java/com/example/SpringBootJdbcDemoApplication.java

package com.example;import com.alibaba.druid.pool.DruidDataSource;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.Bean;import org.springframework.core.env.Environment;import javax.sql.DataSource;/** * Created by tom on 2017/8/31. */@SpringBootApplicationpublic class SpringBootJdbcDemoApplication {    public static void main(String[] args) {        SpringApplication.run(SpringBootJdbcDemoApplication.class, args);    }    @Autowired    private Environment env;    @Bean    public DataSource dataSource() {        DruidDataSource dataSource = new DruidDataSource();        dataSource.setUrl(env.getProperty("spring.datasource.url"));        dataSource.setUsername(env.getProperty("spring.datasource.username"));//用户名        dataSource.setPassword(env.getProperty("spring.datasource.password"));//密码        dataSource.setInitialSize(2);        dataSource.setMaxActive(20);        dataSource.setMinIdle(0);        dataSource.setMaxWait(60000);        dataSource.setValidationQuery("SELECT 1");        dataSource.setTestOnBorrow(false);        dataSource.setTestWhileIdle(true);        dataSource.setPoolPreparedStatements(false);        return dataSource;    }}

你也可以用别的:
<dependency>    <groupId>commons-dbcp</groupId>    <artifactId>commons-dbcp</artifactId>    <version>1.4</version></dependency>

    @Bean    public DataSource dataSource() {        BasicDataSource dataSource = new BasicDataSource();        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));        dataSource.setUrl(env.getProperty("spring.datasource.url"));        dataSource.setUsername(env.getProperty("spring.datasource.username"));        dataSource.setPassword(env.getProperty("spring.datasource.password"));        return dataSource;    }



下面是完整项目结构:




原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 被刺猬的刺扎了怎么办 买电脑被坑了怎么办 买电脑被坑了怎么办啊 在电脑城被坑了怎么办 小狗20天不睁眼怎么办 金星秀停播沈南怎么办 干了活拿不到钱怎么办 干完活要不到钱怎么办 让蚊子咬了很痒怎么办 秋天被蚊子咬了怎么办 练芭蕾脚背太硬怎么办 杨梅酒里的杨梅怎么办 月经期喝了啤酒怎么办 泡过酒的樱桃怎么办 泡了酒的桑葚怎么办 不知怀孕喝了酒怎么办 香氛蜡烛记忆环怎么办 我吃了马兜铃怎么办呀 肝肾衰弱有毒素怎么办 肾阴虚阳虚都有怎么办 吃辣刺激胃疼怎么办 舌头没有舌苔有裂纹疼痛怎么办 舌苔厚黄是怎么回事且口臭怎么办 舌苔厚白是怎么回事且口臭怎么办 长期有舌苔白厚怎么办 小孩的舌苔厚白怎么办 口苦口臭舌苔黄怎么办 婴儿的舌苔厚白怎么办 舌苔黄厚口臭痒怎么办 想让月经提前来怎么办 宝宝拉肚子怎么办吃什么好 投资p2p跑路了怎么办 借钱不还怎么办最有效 朋友借小钱不还怎么办 网络上贷款不还怎么办 网贷实在还不了怎么办 娱乐平台跑路了怎么办 360借条被拒了怎么办 网贷注册太多了怎么办 汽车大绿本丢了怎么办 网贷平台跑路怎么办