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
表,包含属性name
、age
,下面来编写数据访问对象和单元测试用例。
- 定义包含有插入、删除、查询的抽象接口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; }
下面是完整项目结构:
- springboot【8】数据访问之JdbcTemplate访问数据库
- Spring 之数据访问 JdbcTemplate
- SpringBoot之数据访问
- SpringBoot之数据访问操作
- 使用jdbctemplate访问数据库
- springboot【11】数据访问之NoSQL数据库redis
- springboot【12】数据访问之NoSQL数据库MongoDB
- 013. Spring JdbcTemplate访问数据库
- springboot【13】数据访问之整合Mybatis
- Springboot入门之数据访问层
- SpringBoot-访问MySQL数据库
- SpringBoot的数据访问
- Spring Boot 配置JdbcTemplate访问数据库
- Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot中使用JdbcTemplate访问数据库
- spring boot(6)-JdbcTemplate访问数据库
- Spring Boot中使用JdbcTemplate访问数据库
- Spring Boot中使用JdbcTemplate访问数据库
- CC2640R2F BLE5.0 下载运行第一个程序(simple_peripheral)
- 责任链模式
- ±1RMQ(约束RMQ)
- 共享 load事件--addLoadEvent
- ArcGIS for Android 离线数据空间分析--叠加分析
- springboot【8】数据访问之JdbcTemplate访问数据库
- Mabatis学习所碰到的问题(1)
- 使用Eclipse的maven构建一个web项目
- 【Tomcat】-- 小程序开发 tomcat 申请阿里云HTTPS配置
- echarts-2.2.7柱状图隐藏y轴和x轴
- CodeForces
- Android中服务器端与客户端交互
- 面试知识点总结
- 一个能在线处理json等程序员常用功能的网站