Spring Boot 揭秘与实战(二) 数据存储篇
来源:互联网 发布:淘宝网信鸽鸽具用品 编辑:程序博客网 时间:2024/06/06 01:25
- 环境依赖
- 数据源
- 方案一 使用 Spring Boot 默认配置
- 方案二 手动创建
- SQL语句初始化
- 使用JdbcTemplate操作
- 总结
- 源代码
文章链接:http://blog.720ui.com/2016/springboot_02_data_jdbc/
本文讲解 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语句初始化
先初始化需要用到的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](https://github.com/lianggzone/springboot-action)
(完)
阅读全文
1 0
- Spring Boot 揭秘与实战(二) 数据存储篇
- Spring Boot 揭秘与实战之数据存储篇 - MySQL
- Spring Boot 揭秘与实战(七) 实用技术篇
- Spring Boot 揭秘与实战(九) 应用监控篇
- Spring Boot揭秘与实战
- [转]Spring Boot 揭秘与实战(一) 快速上手
- Spring Boot实战(二)
- Spring Boot干货系列:(十一)数据存储篇-Spring Boot整合Mybatis通用Mapper插件
- spring boot学习二:Spring Boot自动装配分析与实战
- Spring Boot实战之项目搭建(二)
- spring boot实战二 事件监听
- Spring Boot学习入门篇(二)--使用Spring Boot
- Spring Boot实战(三)
- Spring boot(二)
- Spring Boot(二)
- Spring Boot实战与原理分析
- Spring Boot与Activiti集成实战
- 《01.Spring Boot实战:Spring Boot入门篇》
- RxAndroid菜鸟必入
- PHP ---- var_dump(),echo,print_r()的区别
- 回溯法 解决二叉树中找一条和为固定数值的路径(java)
- 设计模式介绍之二:单例模式(Singleton)
- JPA-EntityManager
- Spring Boot 揭秘与实战(二) 数据存储篇
- 【系统学习SpringBoot】springBoot 入门篇
- js中判断客户端有无安装Adobe 并指引用户安装
- Python-22 文件系统:os模块
- 【干货合集】阿里云专家诠释持续集成与云端交付的正确姿势
- 设计模式-原型模式-prototype-python
- Qt加载翻译文件
- 2017-08-03 面试记录(铃声多多)
- java_UML:继承/泛化、实现、依赖、关联、聚合、组合的联系与区别