一:项目结构:

:pom文件如下:

  1. <parent>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-parent</artifactId>
  4. <version>2.0.4.RELEASE</version>
  5. </parent>
  6.  
  7. <dependencies>
  8. <!-- Spring-Mybatis -->
  9. <dependency>
  10. <groupId>org.mybatis.spring.boot</groupId>
  11. <artifactId>mybatis-spring-boot-starter</artifactId>
  12. <version>1.3.0</version>
  13. </dependency>
  14. <!-- jdbcTemplate -->
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-jdbc</artifactId>
  18. </dependency>
  19.  
  20. <!-- MySQL连接 -->
  21. <dependency>
  22. <groupId>mysql</groupId>
  23. <artifactId>mysql-connector-java</artifactId>
  24. <scope>runtime</scope>
  25. </dependency>
  26. <!-- Add typical dependencies for a web application -->
  27. <dependency>
  28. <groupId>org.springframework.boot</groupId>
  29. <artifactId>spring-boot-starter-web</artifactId>
  30. </dependency>
  31.  
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-test</artifactId>
  35. <scope>test</scope>
  36. </dependency>
  37.  
  38. </dependencies>

三:数据库配置:

  1. spring:
  2. datasource:
  3. driver-class-name: com.mysql.jdbc.Driver
  4. url: jdbc:mysql://192.168.1.20:3306/test
  5. username: root
  6. password: root123

四:代码说明:

最开始使用mybati比较麻烦,各种配置文件、实体类、dao层映射关联、还有一大推其它配置。当然mybatis也发现了这种弊端,初期开发了generator可以根据表结果自动生产实体类、配置文件和dao层代码,可以减轻一部分开发量;后期也进行了大量的优化可以使用注解了。

于是两种使用方式都介绍一下,一、无配置注解版 二、配置文件版

1.无配置文件注解版
加入配置文件
————————————————

  1. 实体类User.class
  2.  
  3. package cn.saytime.bean;
  4.  
  5. import java.util.Date;
  6.  
  7. /**
  8. * @ClassName cn.saytime.bean.User
  9. * @Description
  10. * @date 2017-07-04 22:47:28
  11. */
  12. public class User {
  13.  
  14. private int id;
  15. private String username;
  16. private int age;
  17. private Date ctm;
  18.  
  19. public User() {
  20. }
  21.  
  22. public User(String username, int age) {
  23. this.username = username;
  24. this.age = age;
  25. this.ctm = new Date();
  26. }
  27.  
  28. // Getter、Setter
  1. package cn.saytime.mapper;
  2.  
  3. import cn.saytime.bean.User;
  4. import org.apache.ibatis.annotations.Delete;
  5. import org.apache.ibatis.annotations.Insert;
  6. import org.apache.ibatis.annotations.Param;
  7. import org.apache.ibatis.annotations.Select;
  8. import org.apache.ibatis.annotations.Update;
  9.  
  10. import java.util.List;
  11.  
  12. // @Mapper 这里可以使用@Mapper注解,但是每个mapper都加注解比较麻烦,所以统一配置@MapperScan在扫描路径在application类中
  13. public interface UserMapper {
  14.  
  15. @Select("SELECT * FROM tb_user WHERE id = #{id}")
  16. User getUserById(Integer id);
  17.  
  18. @Select("SELECT * FROM tb_user")
  19. public List<User> getUserList();
  20.  
  21. @Insert("insert into tb_user(username, age, ctm) values(#{username}, #{age}, now())")
  22. public int add(User user);
  23.  
  24. @Update("UPDATE tb_user SET username = #{user.username} , age = #{user.age} WHERE id = #{id}")
  25. public int update(@Param("id") Integer id, @Param("user") User user);
  26.  
  27. @Delete("DELETE from tb_user where id = #{id} ")
  28. public int delete(Integer id);
  29.  
  30. ————————————————
  1. UserService.class
  2.  
  3. package cn.saytime.service;
  4.  
  5. import cn.saytime.bean.User;
  6. import org.springframework.stereotype.Service;
  7.  
  8. import java.util.List;
  9.  
  10. /**
  11. * @ClassName cn.saytime.service.UserService
  12. * @Description
  13. */
  14. public interface UserService {
  15.  
  16. User getUserById(Integer id);
  17.  
  18. public List<User> getUserList();
  19.  
  20. public int add(User user);
  21.  
  22. public int update(Integer id, User user);
  23.  
  24. public int delete(Integer id);
  1. UserServiceimpl.class
  2.  
  3. package cn.saytime.service.impl;
  4.  
  5. import cn.saytime.bean.User;
  6. import cn.saytime.mapper.UserMapper;
  7. import cn.saytime.service.UserService;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.stereotype.Service;
  10.  
  11. import java.util.List;
  12.  
  13. /**
  14. * @ClassName cn.saytime.service.impl.UserServiceImpl
  15. * @Description
  16. */
  17. @Service
  18. public class UserServiceImpl implements UserService {
  19.  
  20. @Autowired
  21. private UserMapper userMapper;
  22.  
  23. @Override
  24. public User getUserById(Integer id) {
  25. return userMapper.getUserById(id);
  26. }
  27.  
  28. @Override
  29. public List<User> getUserList() {
  30. return userMapper.getUserList();
  31. }
  32.  
  33. @Override
  34. public int add(User user) {
  35. return userMapper.add(user);
  36. }
  37.  
  38. @Override
  39. public int update(Integer id, User user) {
  40. return userMapper.update(id, user);
  41. }
  42.  
  43. @Override
  44. public int delete(Integer id) {
  45. return userMapper.delete(id);
  46. }
  47. }
  1. JsonResult.class 通用json返回类:
  2.  
  3. package cn.saytime.bean;
  4.  
  5. public class JsonResult {
  6.  
  7. private String status = null;
  8.  
  9. private Object result = null;
  10.  
  11. public JsonResult status(String status) {
  12. this.status = status;
  13. return this;
  14. }
  15.  
  16. // Getter Setter
  1. UserController.classRestful风格)
  2.  
  3. package cn.saytime.web;
  4.  
  5. import cn.saytime.bean.JsonResult;
  6. import cn.saytime.bean.User;
  7. import cn.saytime.service.UserService;
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.http.HttpStatus;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.web.bind.annotation.PathVariable;
  12. import org.springframework.web.bind.annotation.RequestBody;
  13. import org.springframework.web.bind.annotation.RequestMapping;
  14. import org.springframework.web.bind.annotation.RequestMethod;
  15. import org.springframework.web.bind.annotation.RequestParam;
  16. import org.springframework.web.bind.annotation.RestController;
  17.  
  18. import java.util.List;
  19.  
  20. /**
  21. * @ClassName cn.saytime.web.UserController
  22. * @Description
  23. * @date 2017-07-04 22:46:14
  24. */
  25. @RestController
  26. public class UserController {
  27.  
  28. @Autowired
  29. private UserService userService;
  30.  
  31. /**
  32. * 根据ID查询用户
  33. * @param id
  34. * @return
  35. */
  36. @RequestMapping(value = "user/{id}", method = RequestMethod.GET)
  37. public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
  38. JsonResult r = new JsonResult();
  39. try {
  40. User user = userService.getUserById(id);
  41. r.setResult(user);
  42. r.setStatus("ok");
  43. } catch (Exception e) {
  44. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  45. r.setStatus("error");
  46. e.printStackTrace();
  47. }
  48. return ResponseEntity.ok(r);
  49. }
  50.  
  51. /**
  52. * 查询用户列表
  53. * @return
  54. */
  55. @RequestMapping(value = "users", method = RequestMethod.GET)
  56. public ResponseEntity<JsonResult> getUserList (){
  57. JsonResult r = new JsonResult();
  58. try {
  59. List<User> users = userService.getUserList();
  60. r.setResult(users);
  61. r.setStatus("ok");
  62. } catch (Exception e) {
  63. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  64. r.setStatus("error");
  65. e.printStackTrace();
  66. }
  67. return ResponseEntity.ok(r);
  68. }
  69.  
  70. /**
  71. * 添加用户
  72. * @param user
  73. * @return
  74. */
  75. @RequestMapping(value = "user", method = RequestMethod.POST)
  76. public ResponseEntity<JsonResult> add (@RequestBody User user){
  77. JsonResult r = new JsonResult();
  78. try {
  79. int orderId = userService.add(user);
  80. if (orderId < 0) {
  81. r.setResult(orderId);
  82. r.setStatus("fail");
  83. } else {
  84. r.setResult(orderId);
  85. r.setStatus("ok");
  86. }
  87. } catch (Exception e) {
  88. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  89. r.setStatus("error");
  90.  
  91. e.printStackTrace();
  92. }
  93. return ResponseEntity.ok(r);
  94. }
  95.  
  96. /**
  97. * 根据id删除用户
  98. * @param id
  99. * @return
  100. */
  101. @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
  102. public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
  103. JsonResult r = new JsonResult();
  104. try {
  105. int ret = userService.delete(id);
  106. if (ret < 0) {
  107. r.setResult(ret);
  108. r.setStatus("fail");
  109. } else {
  110. r.setResult(ret);
  111. r.setStatus("ok");
  112. }
  113. } catch (Exception e) {
  114. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  115. r.setStatus("error");
  116.  
  117. e.printStackTrace();
  118. }
  119. return ResponseEntity.ok(r);
  120. }
  121.  
  122. /**
  123. * 根据id修改用户信息
  124. * @param user
  125. * @return
  126. */
  127. @RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
  128. public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
  129. JsonResult r = new JsonResult();
  130. try {
  131. int ret = userService.update(id, user);
  132. if (ret < 0) {
  133. r.setResult(ret);
  134. r.setStatus("fail");
  135. } else {
  136. r.setResult(ret);
  137. r.setStatus("ok");
  138. }
  139. } catch (Exception e) {
  140. r.setResult(e.getClass().getName() + ":" + e.getMessage());
  141. r.setStatus("error");
  142.  
  143. e.printStackTrace();
  144. }
  145. return ResponseEntity.ok(r);
  146. }
  147.  
  148. }
  1. Application.java
  2.  
  3. package cn.saytime;
  4.  
  5. import org.mybatis.spring.annotation.MapperScan;
  6. import org.springframework.boot.SpringApplication;
  7. import org.springframework.boot.autoconfigure.SpringBootApplication;
  8.  
  9. @SpringBootApplication
  10. @MapperScan("cn.saytime.mapper")
  11. public class SpringbootMybaitsApplication {
  12.  
  13. public static void main(String[] args) {
  14. SpringApplication.run(SpringbootMybaitsApplication.class, args);
  15. }

测试:

使用PostMan通过测试: http://localhost:8080/user/1

2.配置文件版

加入配置文件

代码部分,相比于上面那种方式,改变的只有配置文件以及下面几个部分UserMapper.class

  1. package cn.saytime.mapper;
  2.  
  3. import cn.saytime.bean.User;
  4. import org.apache.ibatis.annotations.Delete;
  5. import org.apache.ibatis.annotations.Insert;
  6. import org.apache.ibatis.annotations.Param;
  7. import org.apache.ibatis.annotations.Select;
  8. import org.apache.ibatis.annotations.Update;
  9. import org.springframework.stereotype.Repository;
  10.  
  11. import java.util.List;
  12.  
  13. /**
  14. * @ClassName cn.saytime.mapper.UesrMapper
  15. * @Description
  16. */
  17. @Repository
  18. public interface UserMapper {
  19.  
  20. User getUserById(Integer id);
  21.  
  22. public List<User> getUserList();
  23.  
  24. public int add(User user);
  25.  
  26. public int update(@Param("id") Integer id, @Param("user") User user);
  27.  
  28. public int delete(Integer id);
  29.  
  30. }
  31.  
  32. UserServiceImpl类:
  1.  

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

  1.  

import com.demo.dao.UserDao;
import com.demo.mapper.User;
import com.demo.mapper.UserMapper1;
import com.demo.service.UserService;

  1.  

@Service
public class UserServiceImpl implements UserService{

@Autowired
private UserDao userDao;

@Autowired
private UserMapper1 userMapper;

  1.  

@Override
public User getUserById(Integer id) {
return userMapper.getUserById(id);
}

  1.  

@Override
public List<User> getUserList() {
return userMapper.getUserList();
}

}

  1.  
  1. mybatis-config.xml
  2.  
  3. <?xml version="1.0" encoding="UTF-8" ?>
  4. <!DOCTYPE configuration
  5. PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  6. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  7. <configuration>
  8. <typeAliases>
  9. </typeAliases>
  10. </configuration>
  1. userMapper.xml
  2.  
  3. <?xml version="1.0" encoding="UTF-8"?>
  4. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  5. <mapper namespace="cn.saytime.mapper.UserMapper" >
  6. <resultMap id="BaseResultMap" type="cn.saytime.bean.User" >
  7. <id column="id" property="id" jdbcType="INTEGER" />
  8. <result column="username" property="username" jdbcType="VARCHAR" />
  9. <result column="age" property="age" jdbcType="INTEGER" />
  10. <result column="ctm" property="ctm" jdbcType="TIMESTAMP"/>
  11. </resultMap>
  12.  
  13. <sql id="Base_Column_List" >
  14. id, username, age, ctm
  15. </sql>
  16.  
  17. <select id="getUserList" resultMap="BaseResultMap" >
  18. SELECT
  19. <include refid="Base_Column_List" />
  20. FROM tb_user
  21. </select>
  22.  
  23. <select id="getUserById" parameterType="java.lang.Integer" resultMap="BaseResultMap" >
  24. SELECT
  25. <include refid="Base_Column_List" />
  26. FROM tb_user
  27. WHERE id = #{id}
  28. </select>
  29.  
  30. <insert id="add" parameterType="cn.saytime.bean.User" >
  31. INSERT INTO
  32. tb_user
  33. (username,age,ctm)
  34. VALUES
  35. (#{username}, #{age}, now())
  36. </insert>
  37.  
  38. <update id="update" parameterType="java.util.Map" >
  39. UPDATE
  40. tb_user
  41. SET
  42. username = #{user.username},age = #{user.age}
  43. WHERE
  44. id = #{id}
  45. </update>
  46.  
  47. <delete id="delete" parameterType="java.lang.Integer" >
  48. DELETE FROM
  49. tb_user
  50. WHERE
  51. id = #{id}
  52. </delete>
  53. </mapper>

测试方法同上:http://localhost:8080/user/1

五、简要说明:
不知道大家有没有注意到一点,就是引入Springboot-mybatis依赖的时候,并不是spring官方的starter,往常的springboot集成的依赖,比如web,redis等,groupId以及artifactId的地址如下:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
而这里是mybatis为spring提供的starter依赖,所以依赖地址是:

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
而且值得注意的是,这里必须要指定版本号,往常我们使用springboot之所以不需要指定版本号,是因为我们引入的Maven Parent 中指定了SpringBoot的依赖,SpringBoot官方依赖Pom文件中已经指定了它自己集成的第三方依赖的版本号,对于Mybatis,Spring官方并没有提供自己的starter,所以必须跟正常的maven依赖一样,要加版本号。
————————————————

SpringBoot(五) SpringBoot整合mybatis的更多相关文章

  1. SpringBoot 2.X整合Mybatis

    1.创建工程环境 勾选Web.Mybatis.MySQL,如下 依赖如下 <dependency> <groupId>org.springframework.boot</ ...

  2. 【springboot spring mybatis】看我怎么将springboot与spring整合mybatis与druid数据源

    目录 概述 1.mybatis 2.druid 壹:spring整合 2.jdbc.properties 3.mybatis-config.xml 二:java代码 1.mapper 2.servic ...

  3. SpringBoot当中如何整合mybatis和注入

    [学习笔记] 6.整合mybatis和注入: 马克-to-win@马克java社区: 根据第3部分的helloworld例子,用那个项目做底子.pom.xml只需要加入mybatis和mysql的部分 ...

  4. springboot笔记07——整合MyBatis

    前言 Springboot 整合 MyBatis 有两种方式,分别是:"全注解版" 和 "注解.xml混合版". 创建项目 创建Springboot项目,选择依 ...

  5. springboot学习2 整合mybatis

    springboot整合mybatis 一.添加mybatis和数据库连接的依赖 <!--整合mybatis--> <dependency> <groupId>or ...

  6. SpringBoot学习之整合Mybatis

    本博客使用IDEA开发工具,通过Maven构建SpringBoot项目,初始化项目添加的依赖有:spring-boot-starter-jdbc.spring-boot-starter-web.mys ...

  7. SpringBoot | 3.2 整合MyBatis

    目录 前言 1. 导入MyBatis场景 1.1 初始化导向 1.2 手动导入 2. *MyBatis自动配置原理 3. 全局配置文件 @Mapper @MapperScan 3.1 配置模式 3.2 ...

  8. 利用IDEA搭建SpringBoot项目,整合mybatis

    一.配置文件.启动项目 生成之后这几个文件可以删掉的 配置application spring.datasource.url=jdbc:mysql://localhost:3306/test?serv ...

  9. SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

    原文链接 我们这一篇博客讲的是如何整合Springboot和Mybatis框架,然后使用generator自动生成mapper,pojo等文件.然后再使用阿里巴巴提供的开源连接池druid,这个连接池 ...

  10. SpringBoot学习:整合Mybatis,使用HikariCP超高性能数据源

    一.添加pom依赖jar包: <!--整合mybatis--> <dependency> <groupId>org.mybatis.spring.boot</ ...

随机推荐

  1. React 从入门到进阶之路(一)

    在开始 React 学习之前我们先进入官网 https://react.docschina.org/ 看看官方对 React 的解释:React 是用于构建用户界面的JavaScript 库.我们只需 ...

  2. 深入理解 Java 异常

  3. Android Fragment 隐藏或显示时调用的生命周期方法

    Fragment使用方式大体分两种: 大家要注意不同的Fragment使用方法,Fragment隐藏和显示调用的生命周期方法是不同的,以下是Fragment显示隐藏调用的方法: //判断是否展示—与V ...

  4. .net core 2.1 Swagger 配置

    1.先创建 .net core Web 应用程序,选择API 2.安装 Nuget 包:Swashbuckle.AspNetCore Install-Package Swashbuckle.AspNe ...

  5. XAF导航系统介绍

    Navigation System 导航系统 10 min to read 阅读时长10分钟 This topic introduces the concept of the navigation s ...

  6. 网络协议 2 - IP 地址和 MAC 地址

    了解完网络协议,我们会发现,网络通信的五层模型里,有两个很重要的概念:IP 地址和 MAC 地址. 那么 IP 地址是怎么来的,又是怎么没的?MAC 地址与 IP 地址又有什么区别? 这回答上面问题前 ...

  7. idea找不到terminal

    起因是这样的,我要用命令行,懒,不想开cmd但是该死的我的idea找不见terminal,好奇怪哦,于是我查了一下,原来设置它蒙蔽了我的眼. 下面给出流程: 一般像我这样比较好学的好孩子不懂就比较喜欢 ...

  8. CodeForces - 1243D (思维+并查集)

    题意 https://vjudge.net/problem/CodeForces-1243D 有一张完全图,n个节点 有m条边的边权为1,其余的都为0 这m条边会给你 问你这张图的最小生成树的权值 思 ...

  9. Windows 10 任务栏添加网易云音乐控制按钮

      软件背景: 算是老帖新发,之前有朋友分享过一个很好用的工具,但可能是因为网易云软件更新后,导致控件失灵了,只剩下歌词控件有用了,所以今天用python重新写了一个小工具,发出来分享给大家,附上之前 ...

  10. Navicat Premium 破解方法

    最新Navicat Premium12 破解方法,亲测可用 1.下载Navicat Premium 官网https://www.navicat.com.cn/下载最新版本下载安装(文末,网盘地址有64 ...