Spring boot +Mybatis 实战(完整版)

个人开源项目

springboot+mybatis+thymeleaf+docker构建的个人站点开源项目(集成了个人主页、个人作品、个人博客)

更多干货

Spring Boot快速入门 
Spring Boot开发Web应用 
Spring Boot工程结构推荐 
Spring Boot构建RESTful API与单元测试 
Spring Boot中使用Swagger2构建强大的RESTful API文档 
Spring Boot中使用JdbcTemplate访问数据库 
Spring Boot中使用Spring-data-jpa让数据访问更简单、更优雅 
Spring Boot多数据源配置与使用 
Spring Boot日志管理 
Spring Boot中使用Redis数据库 
Spring Boot中使用MongoDB数据库 
Spring Boot中Web应用的统一异常处理 
Spring Boot属性配置文件详解 
Spring Boot中使用@Scheduled创建定时任务 
Spring Boot中使用@Async实现异步调用 
Spring boot Mybatis 整合(注解版) 
springboot事务管理详解 
springboot中使用Mybatis注解配置详解

springboot2.0 Mybatis 整合 (springboot2.0版本)

正题

本项目使用的环境:

  • 开发工具:Intellij IDEA 2017.1.3
  • springboot: 1.5.6
  • jdk:1.8.0_161
  • maven:3.3.9

额外功能

  • PageHelper 分页插件
  • mybatis generator 自动生成代码插件

步骤: 
1.创建一个springboot项目: 
这里写图片描述
2.创建项目的文件结构以及jdk的版本 
这里写图片描述 
3.选择项目所需要的依赖 
这里写图片描述
这里写图片描述
然后点击finish

5.看一下文件的结构: 
这里写图片描述

6.查看一下pom.xml:


 
 
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0 </modelVersion>
  5. <groupId>com.winter </groupId>
  6. <artifactId>springboot-mybatis-demo </artifactId>
  7. <version>0.0.1-SNAPSHOT </version>
  8. <packaging>jar </packaging>
  9. <name>springboot-mybatis-demo </name>
  10. <description>Demo project for Spring Boot </description>
  11. <parent>
  12. <groupId>org.springframework.boot </groupId>
  13. <artifactId>spring-boot-starter-parent </artifactId>
  14. <version>1.5.6.RELEASE </version>
  15. <relativePath/> <!-- lookup parent from repository -->
  16. </parent>
  17. <properties>
  18. <project.build.sourceEncoding>UTF-8 </project.build.sourceEncoding>
  19. <project.reporting.outputEncoding>UTF-8 </project.reporting.outputEncoding>
  20. <java.version>1.7 </java.version>
  21. </properties>
  22. <dependencies>
  23. <dependency>
  24. <groupId>org.mybatis.spring.boot </groupId>
  25. <artifactId>mybatis-spring-boot-starter </artifactId>
  26. <version>1.3.0 </version>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot </groupId>
  30. <artifactId>spring-boot-starter-thymeleaf </artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot </groupId>
  34. <artifactId>spring-boot-starter-web </artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot </groupId>
  38. <artifactId>spring-boot-starter-test </artifactId>
  39. <scope>test </scope>
  40. </dependency>
  41. <dependency>
  42. <groupId>mysql </groupId>
  43. <artifactId>mysql-connector-java </artifactId>
  44. <version>5.1.35 </version>
  45. </dependency>
  46. <!-- alibaba的druid数据库连接池 -->
  47. <dependency>
  48. <groupId>com.alibaba </groupId>
  49. <artifactId>druid </artifactId>
  50. <version>1.0.11 </version>
  51. </dependency>
  52. <dependency>
  53. <groupId>com.fasterxml.jackson.core </groupId>
  54. <artifactId>jackson-core </artifactId>
  55. </dependency>
  56. <dependency>
  57. <groupId>com.fasterxml.jackson.core </groupId>
  58. <artifactId>jackson-databind </artifactId>
  59. </dependency>
  60. <dependency>
  61. <groupId>com.fasterxml.jackson.datatype </groupId>
  62. <artifactId>jackson-datatype-joda </artifactId>
  63. </dependency>
  64. <dependency>
  65. <groupId>com.fasterxml.jackson.module </groupId>
  66. <artifactId>jackson-module-parameter-names </artifactId>
  67. </dependency>
  68. <!-- 分页插件 -->
  69. <dependency>
  70. <groupId>com.github.pagehelper </groupId>
  71. <artifactId>pagehelper-spring-boot-starter </artifactId>
  72. <version>1.1.2 </version>
  73. </dependency>
  74. <!-- alibaba的druid数据库连接池 -->
  75. <dependency>
  76. <groupId>com.alibaba </groupId>
  77. <artifactId>druid-spring-boot-starter </artifactId>
  78. <version>1.1.0 </version>
  79. </dependency>
  80. </dependencies>
  81. <build>
  82. <plugins>
  83. <plugin>
  84. <groupId>org.springframework.boot </groupId>
  85. <artifactId>spring-boot-maven-plugin </artifactId>
  86. </plugin>
  87. <!-- mybatis generator 自动生成代码插件 -->
  88. <plugin>
  89. <groupId>org.mybatis.generator </groupId>
  90. <artifactId>mybatis-generator-maven-plugin </artifactId>
  91. <version>1.3.2 </version>
  92. <configuration>
  93. <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml </configurationFile>
  94. <overwrite>true </overwrite>
  95. <verbose>true </verbose>
  96. </configuration>
  97. </plugin>
  98. </plugins>
  99. </build>
  100. </project>

 

7.项目不使用application.properties文件 而使用更加简洁的application.yml文件: 
将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件, 

 

文件的内容如下:


 
 
  1. server:
  2. port: 8080
  3. spring:
  4. datasource:
  5. name: test
  6. url: jdbc:mysql://127.0.0.1:3306/depot
  7. username: root
  8. password: root
  9. # 使用druid数据源
  10. type: com.alibaba.druid.pool.DruidDataSource
  11. driver-class-name: com.mysql.jdbc.Driver
  12. filters: stat
  13. maxActive: 20
  14. initialSize: 1
  15. maxWait: 60000
  16. minIdle: 1
  17. timeBetweenEvictionRunsMillis: 60000
  18. minEvictableIdleTimeMillis: 300000
  19. validationQuery: select 'x'
  20. testWhileIdle: true
  21. testOnBorrow: false
  22. testOnReturn: false
  23. poolPreparedStatements: true
  24. maxOpenPreparedStatements: 20
  25. mybatis:
  26. mapper-locations: classpath:mapping/*.xml
  27. type-aliases-package: com.winter.model
  28. #pagehelper分页插件
  29. pagehelper:
  30. helperDialect: mysql
  31. reasonable: true
  32. supportMethodsArguments: true
  33. params: count=countSql

 

  • 8.创建数据库:
  • 
       
       
    1. CREATE DATABASE mytest;
    2. CREATE TABLE t_user(
    3. user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    4. user_name VARCHAR( 255) NOT NULL ,
    5. password VARCHAR( 255) NOT NULL ,
    6. phone VARCHAR( 255) NOT NULL
    7. ) ENGINE= INNODB AUTO_INCREMENT= 1000 DEFAULT CHARSET=utf8;

 

9.使用mybatis generator 自动生成代码:

  • 配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml
    
       
       
    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE generatorConfiguration
    3. PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
    4. "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
    5. <generatorConfiguration>
    6. <!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
    7. <classPathEntry location="E:\developer\mybatis-generator-core-1.3.2\lib\mysql-connector-java-5.1.25-bin.jar"/>
    8. <context id="DB2Tables" targetRuntime="MyBatis3">
    9. <commentGenerator>
    10. <property name="suppressDate" value="true"/>
    11. <!-- 是否去除自动生成的注释 true:是 : false:否 -->
    12. <property name="suppressAllComments" value="true"/>
    13. </commentGenerator>
    14. <!--数据库链接URL,用户名、密码 -->
    15. <jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://127.0.0.1/mytest" userId="root" password="root">
    16. </jdbcConnection>
    17. <javaTypeResolver>
    18. <property name="forceBigDecimals" value="false"/>
    19. </javaTypeResolver>
    20. <!-- 生成模型的包名和位置-->
    21. <javaModelGenerator targetPackage="com.winter.model" targetProject="src/main/java">
    22. <property name="enableSubPackages" value="true"/>
    23. <property name="trimStrings" value="true"/>
    24. </javaModelGenerator>
    25. <!-- 生成映射文件的包名和位置-->
    26. <sqlMapGenerator targetPackage="mapping" targetProject="src/main/resources">
    27. <property name="enableSubPackages" value="true"/>
    28. </sqlMapGenerator>
    29. <!-- 生成DAO的包名和位置-->
    30. <javaClientGenerator type="XMLMAPPER" targetPackage="com.winter.mapper" targetProject="src/main/java">
    31. <property name="enableSubPackages" value="true"/>
    32. </javaClientGenerator>
    33. <!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
    34. <table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"> </table>
    35. </context>
    36. </generatorConfiguration>
  • 点击run-Edit Configurations

这里写图片描述

  • 添加配置

这里写图片描述

  • 运行 
    这里写图片描述

    <p>最后生成的文件以及结构:</p>
    </li>
    

这里写图片描述

10. 生成的文件

UserMapper.java


 
 
  1. package com.winter.mapper;
  2. import com.winter.model.User;
  3. public interface UserMapper {
  4. int deleteByPrimaryKey(Integer userId);
  5. int insert(User record);
  6. int insertSelective(User record);
  7. User selectByPrimaryKey(Integer userId);
  8. int updateByPrimaryKeySelective(User record);
  9. int updateByPrimaryKey(User record);
  10. //这个方式我自己加的
  11. List<User> selectAllUser();

User.java


 
 
  1. package com.winter.model;
  2. public class User {
  3. private Integer userId;
  4. private String userName;
  5. private String password;
  6. private String phone;
  7. public Integer getUserId() {
  8. return userId;
  9. }
  10. public void setUserId(Integer userId) {
  11. this.userId = userId;
  12. }
  13. public String getUserName() {
  14. return userName;
  15. }
  16. public void setUserName(String userName) {
  17. this.userName = userName == null ? null : userName.trim();
  18. }
  19. public String getPassword() {
  20. return password;
  21. }
  22. public void setPassword(String password) {
  23. this.password = password == null ? null : password.trim();
  24. }
  25. public String getPhone() {
  26. return phone;
  27. }
  28. public void setPhone(String phone) {
  29. this.phone = phone == null ? null : phone.trim();
  30. }
  31. }

对于sql语句这种黄色的背景,真心是看不下去了(解决方案): 
这里写图片描述

UserMapper.xml


 
 
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
  3. <mapper namespace="com.winter.mapper.UserMapper" >
  4. <resultMap id="BaseResultMap" type="com.winter.model.User" >
  5. <id column="user_id" property="userId" jdbcType="INTEGER" />
  6. <result column="user_name" property="userName" jdbcType="VARCHAR" />
  7. <result column="password" property="password" jdbcType="VARCHAR" />
  8. <result column="phone" property="phone" jdbcType="VARCHAR" />
  9. </resultMap>
  10. <sql id="Base_Column_List" >
  11. user_id, user_name, password, phone
  12. </sql>
  13. <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
  14. select
  15. <include refid="Base_Column_List" />
  16. from t_user
  17. where user_id = #{userId,jdbcType=INTEGER}
  18. </select>
  19. <!-- 这个方法是我自己加的 -->
  20. <select id="selectAllUser" resultMap="BaseResultMap">
  21. select
  22. <include refid="Base_Column_List" />
  23. from t_user
  24. </select>
  25. <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
  26. delete from t_user
  27. where user_id = #{userId,jdbcType=INTEGER}
  28. </delete>
  29. <insert id="insert" parameterType="com.winter.model.User" >
  30. insert into t_user (user_id, user_name, password,
  31. phone)
  32. values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
  33. #{phone,jdbcType=VARCHAR})
  34. </insert>
  35. <insert id="insertSelective" parameterType="com.winter.model.User" >
  36. insert into t_user
  37. <trim prefix="(" suffix=")" suffixOverrides="," >
  38. <if test="userId != null" >
  39. user_id,
  40. </if>
  41. <if test="userName != null" >
  42. user_name,
  43. </if>
  44. <if test="password != null" >
  45. password,
  46. </if>
  47. <if test="phone != null" >
  48. phone,
  49. </if>
  50. </trim>
  51. <trim prefix="values (" suffix=")" suffixOverrides="," >
  52. <if test="userId != null" >
  53. #{userId,jdbcType=INTEGER},
  54. </if>
  55. <if test="userName != null" >
  56. #{userName,jdbcType=VARCHAR},
  57. </if>
  58. <if test="password != null" >
  59. #{password,jdbcType=VARCHAR},
  60. </if>
  61. <if test="phone != null" >
  62. #{phone,jdbcType=VARCHAR},
  63. </if>
  64. </trim>
  65. </insert>
  66. <update id="updateByPrimaryKeySelective" parameterType="com.winter.model.User" >
  67. update t_user
  68. <set >
  69. <if test="userName != null" >
  70. user_name = #{userName,jdbcType=VARCHAR},
  71. </if>
  72. <if test="password != null" >
  73. password = #{password,jdbcType=VARCHAR},
  74. </if>
  75. <if test="phone != null" >
  76. phone = #{phone,jdbcType=VARCHAR},
  77. </if>
  78. </set>
  79. where user_id = #{userId,jdbcType=INTEGER}
  80. </update>
  81. <update id="updateByPrimaryKey" parameterType="com.winter.model.User" >
  82. update t_user
  83. set user_name = #{userName,jdbcType=VARCHAR},
  84. password = #{password,jdbcType=VARCHAR},
  85. phone = #{phone,jdbcType=VARCHAR}
  86. where user_id = #{userId,jdbcType=INTEGER}
  87. </update>
  88. </mapper>

11.打开类SpringbootMybatisDemoApplication.java,这个是springboot的启动类。我们需要添加点东西:


 
 
  1. package com.winter;
  2. import org.mybatis.spring.annotation.MapperScan;
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. @SpringBootApplication
  6. @MapperScan( "com.winter.mapper") //将项目中对应的mapper类的路径加进来就可以了
  7. public class SpringbootMybatisDemoApplication {
  8. public static void main(String[] args) {
  9. SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
  10. }
  11. }

 

12.到这里所有的搭建工作都完成了,接下来就是测试的工作,没使用junit4进行测试: 
首先看一下完成之后的文件的结构: 
这里写图片描述

 

现在controller,service层的代码都写好:

UserController.java


 
 
  1. package com.winter.Controller;
  2. import com.winter.model.User;
  3. import com.winter.service.UserService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.PathVariable;
  7. import org.springframework.web.bind.annotation.RequestMapping;
  8. import org.springframework.web.bind.annotation.ResponseBody;
  9. /**
  10. * Created by Administrator on 2017/8/16.
  11. */
  12. @Controller
  13. @RequestMapping(value = "/user")
  14. public class UserController {
  15. @Autowired
  16. private UserService userService;
  17. @ResponseBody
  18. @RequestMapping(value = "/add", produces = { "application/json;charset=UTF-8"})
  19. public int addUser(User user){
  20. return userService.addUser(user);
  21. }
  22. @ResponseBody
  23. @RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = { "application/json;charset=UTF-8"})
  24. public Object findAllUser(@PathVariable("pageNum") int pageNum, @PathVariable("pageSize") int pageSize){
  25. return userService.findAllUser(pageNum,pageSize);
  26. }
  27. }

UserService.java


 
 
  1. package com.winter.service;
  2. import com.winter.model.User;
  3. import java.util.List;
  4. /**
  5. * Created by Administrator on 2017/8/16.
  6. */
  7. public interface UserService {
  8. int addUser(User user);
  9. List<User> findAllUser(int pageNum, int pageSize);
  10. }

UserServiceImpl.java


 
 
  1. package com.winter.service.impl;
  2. import com.github.pagehelper.PageHelper;
  3. import com.winter.mapper.UserMapper;
  4. import com.winter.model.User;
  5. import com.winter.service.UserService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.stereotype.Service;
  8. import java.util.List;
  9. /**
  10. * Created by Administrator on 2017/8/16.
  11. */
  12. @Service(value = "userService")
  13. public class UserServiceImpl implements UserService {
  14. @Autowired
  15. private UserMapper userMapper; //这里会报错,但是并不会影响
  16. @Override
  17. public int addUser(User user) {
  18. return userMapper.insertSelective(user);
  19. }
  20. /*
  21. * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
  22. * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
  23. * pageNum 开始页数
  24. * pageSize 每页显示的数据条数
  25. * */
  26. @Override
  27. public List<User> findAllUser(int pageNum, int pageSize) {
  28. //将参数传给这个方法就可以实现物理分页了,非常简单。
  29. PageHelper.startPage(pageNum, pageSize);
  30. return userMapper.selectAllUser();
  31. }
  32. }

 

如果强迫症看不下去那个报错:(解决方法) 
这里写图片描述

 

测试我使用了idea一个很用心的功能。 
可以发http请求的插件: 
这里写图片描述

这里写图片描述

点击左侧的运行按钮就可以发送请求了; 
如果返回值正确 说明你已经搭建成功了!!

如果出现mapper注入不了的情况,请检查版本,当前博客的搭建方法只适合1.5.*版本的,如果你的版本是2.0以上的版本,请参照我的另一篇博客的mybatis的配置:springboot2.0整合mybatis

如果大家想使用事务控制的话,请参照Spring boot Mybatis 整合(注解版) ,这个里面就有关于事务控制的使用

源码地址:https://github.com/WinterChenS/springboot-mybatis-demo

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值