一、数据源配置
在我们访问数据库的时候,需要先配置一个数据源,下面分别介绍一下几种不同的数据库配置方式。
首先,为了连接数据库需要引入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/springboot
spring.datasource.username=root
spring.datasource.password=root
spring.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学习
*/
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;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public void create(String name, Integer age) {
jdbcTemplate.update("INSERT INTO USER(NAME, AGE) VALUES(?, ?)", name, age);
}
@Override
public void deleteByName(String name) {
jdbcTemplate.update("DELETE FROM USER WHERE NAME = ?", name);
}
@Override
public Integer getAllUsers() {
return jdbcTemplate.queryForObject("SELECT COUNT(1) FROM USER", Integer.class);
}
@Override
public 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 {
@Autowired
private UserService userService;
@Before
public void setUp(){
// 准备,清空user表
userService.deleteAllUsers();
}
@Test
public 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: true
init-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.
*/
@SpringBootApplication
public 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;
}
下面是完整项目结构: