Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合
文章目录
本文讲解Spring Boot基础下,如何整合MyBatis框架,编写数据访问。
环境依赖
修改 POM 文件,添加mybatis-spring-boot-starter依赖。值得注意的是,可以不添加spring-boot-starter-jdbc。因为,mybatis-spring-boot-starter依赖中存在spring-boot-starter-jdbc。
- <dependency>
- <groupId>org.mybatis.spring.boot</groupId>
- <artifactId>mybatis-spring-boot-starter</artifactId>
- <version>1.1.1</version>
- </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 默认配置
在 src/main/resources/application.properties 中配置数据源信息。
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3307/springboot_db?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
- 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?useUnicode = true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
- 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;
MyBatis整合
方案一 通过注解的方式
实体对象
- public class Author {
- private Long id;
- @JSONField(name="real_name")
- private String realName;
- @JSONField(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
DAO相关
- @Mapper
- public interface AuthorMapper {
- @Insert("insert into t_author(real_name, nick_name) values(#{real_name}, #{nick_name})")
- int add(@Param("realName") String realName, @Param("nickName") String nickName);
- @Update("update t_author set real_name = #{real_name}, nick_name = #{nick_name} where id = #{id}")
- int update(@Param("real_name") String realName, @Param("nick_name") String nickName, @Param("id") Long id);
- @Delete("delete from t_author where id = #{id}")
- int delete(Long id);
- @Select("select id, real_name as realName, nick_name as nickName from t_author where id = #{id}")
- Author findAuthor(@Param("id") Long id);
- @Select("select id, real_name as realName, nick_name as nickName from t_author")
- List<Author> findAuthorList();
- }
Service相关
- @Service
- public class AuthorService {
- @Autowired
- private AuthorMapper authorMapper;
- public int add(String realName, String nickName) {
- return this.authorMapper.add(realName, nickName);
- }
- public int update(String realName, String nickName, Long id) {
- return this.authorMapper.update(realName, nickName, id);
- }
- public int delete(Long id) {
- return this.authorMapper.delete(id);
- }
- public Author findAuthor(Long id) {
- return this.authorMapper.findAuthor(id);
- }
- public List<Author> findAuthorList() {
- return this.authorMapper.findAuthorList();
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController("mybatis.authorController")
- @RequestMapping(value="/data/mybatis/author")
- @MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
- 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");
- try{
- this.authorService.add(realName, nickName);
- }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");
- try{
- this.authorService.update(realName, nickName, author.getId());
- }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("删除错误");
- }
- }
- }
方案二 通过配置文件的方式
实体对象
- public class Author {
- private Long id;
- @JSONField(name="real_name")
- private String realName;
- @JSONField(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
配置相关
在 src/main/resources/mybatis/AuthorMapper.xml 中配置数据源信息。
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
- "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
- <mapper namespace="com.lianggzone.springboot.action.data.mybatis.dao.AuthorMapper2">
- <!-- type为实体类Student,包名已经配置,可以直接写类名 -->
- <resultMap id="authorMap" type="Author">
- <id property="id" column="id" />
- <result property="realName" column="real_name" />
- <result property="nickName" column="nick_name" />
- </resultMap>
- <select id="findAuthor" resultMap="authorMap" resultType="Author">
- select id, real_name, nick_name from t_author where id = #{id}
- </select>
- </mapper>
在 src/main/resources/application.properties 中配置数据源信息。
- mybatis.mapper-locations=classpath*:mybatis/*Mapper.xml
- mybatis.type-aliases-package=com.lianggzone.springboot.action.data.mybatis.entity
DAO相关
- public interface AuthorMapper2 {
- Author findAuthor(@Param("id") Long id);
- }
Service相关
- @Service
- public class AuthorService2 {
- @Autowired
- private AuthorMapper2 authorMapper;
- public Author findAuthor(Long id) {
- return this.authorMapper.findAuthor(id);
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController("mybatis.authorController2")
- @RequestMapping(value="/data/mybatis/author2")
- @MapperScan("com.lianggzone.springboot.action.data.mybatis.dao")
- public class AuthorController2 {
- @Autowired
- private AuthorService2 authorService;
- /**
- * 查询用户信息
- */
- @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;
- }
- }
总结
上面这个简单的案例,让我们看到了 Spring Boot 整合 MyBatis 框架的大概流程。那么,复杂的场景,大家可以参考使用一些比较成熟的插件,例如com.github.pagehelper、mybatis-generator-maven-plugin等。
源代码
相关示例完整代码: springboot-action
(完)

- 版权声明:本文由 梁桂钊 发表于 梁桂钊的博客
- 转载声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证),非商业转载请注明作者及出处,商业转载请联系作者本人。
- 文章标题:Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置
- 文章链接:http://blog.720ui.com/2016/springboot_02_data_datasource/
Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合的更多相关文章
- 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 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置
文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL
文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. 使用JdbcTemplate操作5. 总结 4.1. ...
- 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 揭秘与实战(二) 数据缓存 ...
随机推荐
- Buffer和Stream
Buffer JavaScript 语言自身只有字符串数据类型,没有二进制数据类型.但在处理像TCP流或文件流时,必须使用到二进制数据. 因此在 Node.js中,定义了一个 Buffer 类,该类用 ...
- [Uva P11168] Airport
题目是英文的,这里就不给出来了. 题目的大意是说,在平面上有n个点,要找一条直线,使所有点到直线的平均距离最小,且这些点都在该直线的同一侧(包括直线上). 那么,既然要使距离最小化,还要使所有点一定在 ...
- rsyslog的配置文件使用方法
参考地址: http://www.rsyslog.com/doc/v8-stable/configuration/property_replacer.html rsyslog消息模板的定义规则 &qu ...
- js作用域及闭包
作用域 执行环境是js最为重要的一个概念.执行环境定义了变量或函数有权访问的其他数据,决定了它们各自的行为. 1.全局执行环境就是最外围的一个执行环境,每一个函数都有自己的作用域 2.简单的说局部作用 ...
- Unity中Text中首行缩进两个字符和换行的代码
1.首行缩进两个字符 txt.text=“\u3000\u3000” + str: 2.首行缩进两个字符 将输入法换成全角的,在Text属性面板中添加空格即可. 3.换行 “\n” 补充 Uni ...
- sqlalchemy 简介
#! /usr/bin/env python3 # -*- coding:utf-8 -*- #use SQLAlchemy #ORM:Object-Relational Mapping ,把关系数据 ...
- bootstrap动态生成层级ul-li 新闻预览 常用方法
<div class="row" id="add-withinfosortId-row" style="display: none"& ...
- Eclipse快捷键+遇到补充
MyEclipse 快捷键1(CTRL) Ctrl+1 快速修复Ctrl+D: 删除当前行Ctrl+Q 定位到最后编辑的地方Ctrl+L 定位在某行Ctrl+O 快速显示 OutLineCtrl+T ...
- Java基础-类和对象
类和对象 对象:对象是类的一个实例(对象不是找个女朋友),有状态和行为.例如,一条狗是一个对象,它的状态有:颜色.名字.品种:行为有:摇尾巴.叫.吃等. 类:类是一个模板,它描述一类对象的行为和状态. ...
- Ionic2开发环境搭建、项目创建调试与Android应用的打包、优化
Ionic2开发环境搭建.项目创建调试与Android应用的打包.优化. windows下ionic2开发环境配置步骤如下: 下载node.js环境,稳定版本:v6.9.5 下载android stu ...