本文讲解 Spring Boot 基础下,如何使用 JDBC,配置数据源和通过 JdbcTemplate 编写数据访问。
首先在pom.xml中引入jdbc依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
添加MySql依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.43</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.3</version> </dependency>
在src/main/resources/application.properties中配置数据源信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3307/springbootspring.datasource.username=root spring.datasource.password=root
运行数据库脚本
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `springboot`; DROP TABLE IF EXISTS `t_author`; CREATE TABLE `t_author` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID', `name` varchar(32) NOT NULL COMMENT '测试名称', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
创建实体对象
public class Author {
private long id;//用户ID.
private String name;//测试名称.
// SET和GET方法}Controller层
@RestController@RequestMapping(value="/data/jdbc/author")public class DemoController { @Autowired
private AuthorService AuthorService; /**
* 新增方法
*/
@RequestMapping(method = RequestMethod.POST) public void add(@RequestBody JSONObject jsonObject) {
String id = jsonObject.getString("id");
String name = jsonObject.getString("name");
Author author = new Author(); if (author!=null) {
author.setId(Long.valueOf(id));
}
author.setName(name); try{ this.authorService.add(author);
}catch(Exception e){
e.printStackTrace(); throw new RuntimeException("新增错误");
}
}Service层
public interface BaseAuthorService { int add(Author author);
}service实现类
@Servicepublic class AuthorService implements BaseAuthorService { @Autowired
private AuthorDao authorDao; public Demo add(Long id){ return authorDao.add(id);
}
}DAO层
public interface BaseAuthorDao { int add(Author author);
}Dao层实现类
@Repositorypublic class AuthorDao implements BaseAuthorDao { @Autowired
private AuthorDao authorDao; @Override
public int add(Author author) { return authorDao.add(author);
}
}上面介绍的JdbcTemplate只是最基本的添加操作,更多使用方法请参考:JdbcTemplate API
在Spring Boot中使用Jdbc访问数据库依旧秉持Spring Boot框架的特点:简单。
我们只需要在pom.xml中加入数据库依赖,再到application.properties中配置连接信息,不需要像Spring应用中创建JdbcTemplate的Bean,就可以直接在自己的对象中注入使用。
作者:HOWD
链接:https://www.jianshu.com/p/b4cf505fb40c