Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL
文章目录
本文讲解 Spring Boot 基础下,如何使用 JDBC,配置数据源和通过 JdbcTemplate 编写数据访问。
环境依赖
修改 POM 文件,添加spring-boot-starter-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.35</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.14</version>
- </dependency>
数据源
方案一 使用 Spring Boot 默认配置
使用 Spring Boot 默认配置,不需要在创建 dataSource 和 jdbcTemplate 的 Bean。
在 src/main/resources/application.properties 中配置数据源信息。
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db
- spring.datasource.username=root
- spring.datasource.password=root
方案二 手动创建
在 src/main/resources/config/source.properties 中配置数据源信息。
- # mysql
- source.driverClassName = com.mysql.jdbc.Driver
- source.url = jdbc:mysql://localhost:3306/springboot_db
- source.username = root
- source.password = root
通过 Java Config 创建 dataSource 和jdbcTemplate。
- @Configuration
- @EnableTransactionManagement
- @PropertySource(value = {"classpath:config/source.properties"})
- public class BeanConfig {
- @Autowired
- private Environment env;
- @Bean(destroyMethod = "close")
- public DataSource dataSource() {
- DruidDataSource dataSource = new DruidDataSource();
- dataSource.setDriverClassName(env.getProperty("source.driverClassName").trim());
- dataSource.setUrl(env.getProperty("source.url").trim());
- dataSource.setUsername(env.getProperty("source.username").trim());
- dataSource.setPassword(env.getProperty("source.password").trim());
- return dataSource;
- }
- @Bean
- public JdbcTemplate jdbcTemplate() {
- JdbcTemplate jdbcTemplate = new JdbcTemplate();
- jdbcTemplate.setDataSource(dataSource());
- return jdbcTemplate;
- }
- }
脚本初始化
先初始化需要用到的SQL脚本。
- CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
- USE `springboot_db`;
- DROP TABLE IF EXISTS `t_author`;
- CREATE TABLE `t_author` (
- `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
- `real_name` varchar(32) NOT NULL COMMENT '用户名称',
- `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
使用JdbcTemplate操作
实体对象
- public class Author {
- private Long id;
- private String realName;
- private String nickName;
- // SET和GET方法
- }
DAO相关
- public interface AuthorDao {
- int add(Author author);
- int update(Author author);
- int delete(Long id);
- Author findAuthor(Long id);
- List<Author> findAuthorList();
- }
我们来定义实现类,通过JdbcTemplate定义的数据访问操作。
- @Repository
- public class AuthorDaoImpl implements AuthorDao {
- @Autowired
- private JdbcTemplate jdbcTemplate;
- @Override
- public int add(Author author) {
- return jdbcTemplate.update("insert into t_author(real_name, nick_name) values(?, ?)",
- author.getRealName(), author.getNickName());
- }
- @Override
- public int update(Author author) {
- return jdbcTemplate.update("update t_author set real_name = ?, nick_name = ? where id = ?",
- new Object[]{author.getRealName(), author.getNickName(), author.getId()});
- }
- @Override
- public int delete(Long id) {
- return jdbcTemplate.update("delete from t_author where id = ?", id);
- }
- @Override
- public Author findAuthor(Long id) {
- List<Author> list = jdbcTemplate.query("select * from t_author where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Author.class));
- if(null != list && list.size()>0){
- Author auhtor = list.get(0);
- return auhtor;
- }else{
- return null;
- }
- }
- @Override
- public List<Author> findAuthorList() {
- List<Author> list = jdbcTemplate.query("select * from t_author", new Object[]{}, new BeanPropertyRowMapper<Author>(Author.class));
- return list;
- }
- }
Service相关
- public interface AuthorService {
- int add(Author author);
- int update(Author author);
- int delete(Long id);
- Author findAuthor(Long id);
- List<Author> findAuthorList();
- }
我们来定义实现类,Service层调用Dao层的方法,这个是典型的套路。
- @Service("authorService")
- public class AuthorServiceImpl implements AuthorService {
- @Autowired
- private AuthorDao authorDao;
- @Override
- public int add(Author author) {
- return this.authorDao.add(author);
- }
- @Override
- public int update(Author author) {
- return this.authorDao.update(author);
- }
- @Override
- public int delete(Long id) {
- return this.authorDao.delete(id);
- }
- @Override
- public Author findAuthor(Long id) {
- return this.authorDao.findAuthor(id);
- }
- @Override
- public List<Author> findAuthorList() {
- return this.authorDao.findAuthorList();
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController
- @RequestMapping(value="/data/jdbc/author")
- public class AuthorController {
- @Autowired
- private AuthorService authorService;
- /**
- * 查询用户列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String,Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAuthorList();
- Map<String,Object> param = new HashMap<String,Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查询用户信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if(author == null){
- throw new RuntimeException("查询错误");
- }
- return author;
- }
- /**
- * 新增方法
- */
- @RequestMapping(method = RequestMethod.POST)
- public void add(@RequestBody JSONObject jsonObject) {
- String userId = jsonObject.getString("user_id");
- String realName = jsonObject.getString("real_name");
- String nickName = jsonObject.getString("nick_name");
- Author author = new Author();
- if (author!=null) {
- author.setId(Long.valueOf(userId));
- }
- author.setRealName(realName);
- author.setNickName(nickName);
- try{
- this.authorService.add(author);
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException("新增错误");
- }
- }
- /**
- * 更新方法
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.PUT)
- public void update(@PathVariable Long userId, @RequestBody JSONObject jsonObject) {
- Author author = this.authorService.findAuthor(userId);
- String realName = jsonObject.getString("real_name");
- String nickName = jsonObject.getString("nick_name");
- author.setRealName(realName);
- author.setNickName(nickName);
- try{
- this.authorService.update(author);
- }catch(Exception e){
- e.printStackTrace();
- throw new RuntimeException("更新错误");
- }
- }
- /**
- * 删除方法
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.DELETE)
- public void delete(@PathVariable Long userId) {
- try{
- this.authorService.delete(userId);
- }catch(Exception e){
- throw new RuntimeException("删除错误");
- }
- }
- }
总结
通过,上面这个简单的案例,我们发现 Spring Boot 仍然秉承了 Spring 框架的一贯套路,并简化 Spring 应用的初始搭建以及开发过程。
源代码
相关示例完整代码: springboot-action
(完)

- 版权声明:本文由 梁桂钊 发表于 梁桂钊的博客
- 转载声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证),非商业转载请注明作者及出处,商业转载请联系作者本人。
- 文章标题:Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置
- 文章链接:http://blog.720ui.com/2016/springboot_02_data_datasource/
Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL的更多相关文章
- Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理
文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch
文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB
文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用mongoTemplate操作4. 总结 3.1. 实体对象 3 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - Redis
文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合
文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置
文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门
文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache
文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...
随机推荐
- Shiro集成web环境[Springboot]-基础使用
Shiro集成web环境[Springboot] 1.shiro官网查找依赖的jar,其中shiro-ehcache做授权缓存时使用,另外还需要导入ehcache的jar包 <dependenc ...
- rpc框架实现(持续更新)
网站应用的规模不断扩大,常规的垂直应用架构已无法应对,分布式服务架构以及流动计算架构势在必行,rpc基于长连接的远程过程调用应用而生. 一:A服务调用B服务,整个调用过程,主要经历如下几个步骤:(摘自 ...
- Java获取路径(getResource)
package com.zhi.test; public class PathTest { public static void main(String[] args) { System.out.pr ...
- bzoj1692
题解: 二分最近的不相同 然后hash判断是否相同 然后贪心 代码: #include<bits/stdc++.h> using namespace std; #define ull un ...
- python ----字符串基础练习题30道
1.执行python脚本的两种方式 一种是点开始--运行--cmd 方式(这个操作需要先配置好环境变量path路径)之后运行python 二是直接进安装目录 运行tython软件运行.pycharm ...
- PC/FORTH定点原理
body, table{font-family: 微软雅黑} table{border-collapse: collapse; border: solid gray; border-width: 2p ...
- block,inline-block,行内元素区别及浮动
1.block: 默认占据一行空间,盒子外的元素被迫另起一行 2.inline-block: 行内块盒子,可以设置宽高 3.行内元素: 宽度即使内容宽度,不能设置宽高,如果要设置宽高,需要转换成行内块 ...
- ROS tab键补全操作出现错误
ros tab键补全操作出现错误如下: $ roslaunch sp[rospack] Warning: error while crawling /home/hemudu: boost::files ...
- 对仿真glbl.v文件的理解
Simulation, UniSim, SimPrim - How do I use the "glbl.v" module in a Verilog simulation? De ...
- 从今天开始 每天记录HTML,CSS 部分的学习笔记
从今天开始 每天记录HTML,CSS 部分的学习笔记