原文地址 http://www.cnblogs.com/tomlxq/p/5514658.html
本文将介绍如何将spring boot 与 JdbcTemplate一起工作。
Spring对数据库的操作在jdbc上面做了深层次的封装,使用spring的注入功能,可以把DataSource注册到JdbcTemplate之中。 JdbcTemplate 是在JDBC API基础上提供了更抽象的封装,并提供了基于方法注解的事务管理能力。 通过使用SpringBoot自动配置功能并代替我们自动配置beans. 在maven中,我们需要增加spring-boot-starter-jdbc模块
<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 2016/5/21.
*/
@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;
}
创建实体对象
/src/main/java/com/example/domain/User.java
package com.example.domain;
/**
* Created by tom on 2016/5/21.
*/
public class User
{
private Integer id;
private String name;
private String email;
public User()
{
}
public User(Integer id, String name, String email)
{
this.id = id;
this.name = name;
this.email = email;
}
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
'}';
}
}
创建持久层
有了上面的数据源配置,我们可以注入JdbcTemplate到数据访问组件并与数据库交互。 /src/main/java/com/example/repositories/UserRepository.java
package com.example.repositories;
import com.example.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.*;
import java.util.List;
/**
* Created by tom on 2016/5/21.
*/
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
@Transactional(readOnly = true)
public List<User> findAll() {
return jdbcTemplate.query("select * from users", new UserRowMapper());
}
@Transactional(readOnly = true)
public User findUserById(int id) {
return jdbcTemplate.queryForObject("select * from users where id=?", new Object[]{id}, new UserRowMapper());
}
public User create(final User user) {
final String sql = "insert into users(name,email) values(?,?)";
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection)
throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, user.getName());
ps.setString(2, user.getEmail());
return ps;
}
}, holder);
int newUserId = holder.getKey().intValue();
user.setId(newUserId);
return user;
}
public void delete(final Integer id) {
final String sql = "delete from users where id=?";
jdbcTemplate.update(sql,
new Object[]{id},
new int[]{java.sql.Types.INTEGER});
}
public void update(final User user) {
jdbcTemplate.update(
"update users set name=?,email=? where id=?",
new Object[]{user.getName(), user.getEmail(), user.getId()});
}
}
class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
user.setId(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setEmail(rs.getString("email"));
return user;
}
}
你或许己注意到,大多数时候,我们都在应用中做这些配置的事。
创建单元测试测试我们的持久层方法
/src/test/java/SpringBootJdbcDemoApplicationTests.java
import com.example.SpringBootJdbcDemoApplication;
import com.example.domain.User;
import com.example.repositories.UserRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
import static org.junit.Assert.*;
import static org.junit.Assert.assertEquals;
/**
* Created by tom on 2016/5/21.
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SpringBootJdbcDemoApplication.class)
public class SpringBootJdbcDemoApplicationTests
{
Logger logger= LoggerFactory.getLogger(SpringBootJdbcDemoApplicationTests.class);
@Autowired
private UserRepository userRepository;
@Test public void testAll(){
findAllUsers();
findUserById();
createUser();
}
@Test
public void findAllUsers() {
List<User> users = userRepository.findAll();
assertNotNull(users);
assertTrue(!users.isEmpty());
}
@Test
public void findUserById() {
User user = userRepository.findUserById(1);
assertNotNull(user);
}
private void updateById(Integer id) {
User newUser = new User(id, "JackChen", "JackChen@qq.com");
userRepository.update(newUser);
User newUser2 = userRepository.findUserById(newUser.getId());
assertEquals(newUser.getName(), newUser2.getName());
assertEquals(newUser.getEmail(), newUser2.getEmail());
}
@Test
public void createUser() {
User user = new User(0, "tom", "tom@gmail.com");
User savedUser = userRepository.create(user);
logger.debug("{}",savedUser);
User newUser = userRepository.findUserById(savedUser.getId());
assertEquals("tom", newUser.getName());
assertEquals("tom@gmail.com", newUser.getEmail());
updateById(newUser.getId());
userRepository.delete(newUser.getId());
}
}
相关推荐
简单介绍如何使用Spring Boot使用JdbcTemplate与MySQL进行数据库操作
Spring boot,事物,拦截器,servlet 自动装配,数据源
配制Spring事务和JdbcTemplate使用 配制Spring事务和JdbcTemplate使用
Spring Boot中的JdbcTemplate与MySQL集成
使用Spring的JdbcTemplate调用Oracle的存储过程
https://blog.csdn.net/u012081441/article/details/80746538
Spring Boot实战与原理分析视频课程包含14-18,本视频教程为网络整理,如有侵权,请联系删除。谢谢 Spring Boot实战与原理分析视频课程 课程目录: 1 Spring Boot概述与课程概要介绍20:33 2 Spring4 快速入门59:56...
文中通过示例代码介绍的非常详细,对大家学习或者使用spring boot整合JdbcTemplate具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧
1.3 spring boot起步之Hello World 1.4 Spring Boot返回json数据 1.5 Spring Boot热部署 1.6 Spring Boot使用别的json解析框架 1.7 全局异常捕捉 1.8 Spring Boot datasource - mysql 1.9 JPA - Hibernate 1.10 使用...
SpringBoot 是为了简化 Spring 应用的创建、运行、调试、部署等一系列问题而诞生的产物。本文重点给大家介绍spring boot 使用JdbcTemplate访问数据库,需要的朋友可以参考下
本文介绍在Spring Boot基础下配置数据源和通过 JdbcTemplate 编写数据访问的示例。感兴趣的朋友跟随脚本之家小编一起学习吧
8. Spring boot 使用 JdbcTemplate 保存数据 9. Spring boot 常用配置 10. Spring boot 静态资源处理 11. Srping boot 实现任务调度 12. Spring boot 普通类调用 Bean 13. spring boot 使用模板引擎 14. Spring...
- chapter9-2-2:[Spring Boot与Dubbo中管理服务依赖] ### Spring Cloud构建微服务架构 由于Spring Cloud偏宏观架构,Spring Boot偏微观细节,内容上越来越多,为了两部分内容不互相干扰,所以迁移Spring Cloud...
一套完成的使用Idea开发环境,采用springboot、jdbcTemplate实现的mysql读取webService完成程序。其中,封装了数据读、写、删除的各种操作;访问webservice时,需要使用token认证。 一套很实用、很难得的的基于java...
JdbcTemplate 是在JDBC API基础上提供了更抽象的封装,并提供了基于方法注解的事务管理... 通过使用SpringBoot自动配置功能并代替我们自动配置beans,下面给大家介绍spring boot中使用JdbcTemplate相关知识,一起看看吧
spring boot + JdbcTemplate 使用druid数据源
│ 开篇词 从零开始:为什么要学习 Spring Boot?.mp4 │ 01 家族生态:如何正确理解 Spring 家族的技术体系?.mp4 │ 02 案例驱动:如何剖析一个 Spring Web 应用程序?.mp4 │ 03 多维配置:如何使用 Spring ...
本篇文档主要介绍Spring JDBCTemplate知识。亦可作为Spring JDBCTemplate的API文档。文档中的内容,对于学习Spring JDBCTemplate有很大的帮助,也可帮助他人学习Spring Boot中的JDBCTemplate知识。
Spring Boot+Jpa多数据源配置Demo,可同时支持多种数据库,不同数据库,同时支持不同数据库的JdbcTemplate