springboot---数据整合篇
本文讲解 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---数据整合篇的更多相关文章
- 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. 方案一 通过 ...
- SpringBoot第六篇:整合通用Mapper
作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10876339.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言 在以往的项 ...
- 大数据工具篇之Hive与MySQL整合完整教程
大数据工具篇之Hive与MySQL整合完整教程 一.引言 Hive元数据存储可以放到RDBMS数据库中,本文以Hive与MySQL数据库的整合为目标,详细说明Hive与MySQL的整合方法. 二.安装 ...
- 大数据工具篇之Hive与HBase整合完整教程
大数据工具篇之Hive与HBase整合完整教程 一.引言 最近的一次培训,用户特意提到Hadoop环境下HDFS中存储的文件如何才能导入到HBase,关于这部分基于HBase Java API的写入方 ...
- SpringBoot第七篇:整合Mybatis-Plus
作者:追梦1819 原文:https://www.cnblogs.com/yanfei1819/p/10881666.html 版权声明:本文为博主原创文章,转载请附上博文链接! 引言 一看这个名 ...
- SpringBoot数据访问之整合mybatis注解版
SpringBoot数据访问之整合mybatis注解版 mybatis注解版: 贴心链接:Github 在网页下方,找到快速开始文档 上述链接方便读者查找. 通过快速开始文档,搭建环境: 创建数据库: ...
- 使用VUE+SpringBoot+EasyExcel 整合导入导出数据
使用VUE+SpringBoot+EasyExcel 整合导入导出数据 创建一个普通的maven项目即可 项目目录结构 1 前端 存放在resources/static 下 index.html &l ...
- thymeleaf第二篇:理解原理并为后面springboot进行整合进行铺垫
官方入门之从虚拟商店理解thymeleaf 参考文档: 简单使用Thymeleaf API渲染模板生成静态页面 邮件通知改造之Thymeleaf渲染模板生成静态页面--看懂会帮助理解springboo ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch
文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...
随机推荐
- MVC和观察者模式
用观察者模式实现MVC框架! http://wenku.baidu.com/view/eff8bab069dc5022aaea0007.html 写的不错! Observer和ConcreteObse ...
- spring boot 重定向
/** * 测试各个html文件用. * @param model * @return */ @RequestMapping("home") public String home( ...
- [py]函数小结
函数作用域(函数前向引用) --> 嵌套(递归是一种个特殊的嵌套) --> 递归(回归,递归是一种特殊的迭代) --> 迭代 --> 生成器 --> 匿名函数 递归 一种 ...
- CentOS7下的YUM源服务器搭建详解,过程写的很详细(转)
因为近期公司需要搭建一个YUM源服务器给大量的linux(mini)使用,所以因此在网上找了很多的教程,却没有一个特别详细的,很多都有遗漏,参差不齐.所以,打算自己做完之后方便以后查阅,特出此文档. ...
- Git 系列——第一步安装 Git
之前也没有用过什么版本控制的工具,唯一用过的就是 SVN 了,不过也只是简单的使用而已,比如写好代码就签入,没了?是的,没了. 于是接触到了 Git 这个分布式版本控制软件,接下来就让我们好好学习,天 ...
- SQL substring()函数
①substring()函数是个截取函数,不同的数据库语法有区别 MySQL: SUBSTR( ), SUBSTRING( ) Oracle: SUBSTR( ) SQL Server: SUBSTR ...
- iOS重签名脚本
unzip xxx.ipa //解压ipa rm -rf Payload/ xxx.app/_CodeSignature //删除旧签名 cp newEmbedded.mobileprovision ...
- python使用cx_Oracle连接oracle
1.使用pip命令安装cx_Oracle $ pip install cx_Oracle 2.安装oracle客户端,并添加到path 下载路径: http://www.oracle.com/tech ...
- ABP官方文档翻译 0.0 ABP官方文档翻译目录
一直想学习ABP,但囿于工作比较忙,没有合适的契机,当然最重要的还是自己懒.不知不觉从毕业到参加工作七年了,没留下点儿什么,总感觉很遗憾,所以今天终于卯足劲鼓起勇气开始写博客.有些事能做的很好,但要跟 ...
- 使用vux实现上拉刷新的总结
最近公司在研发app,选择了基于Vue框架的vux组件库,现总结在实现上拉刷新功能遇到的坑: 1.问题:只刷新一次,解决方法:需要自己手动重置状态 this.scrollerStatus.pullup ...