第四篇:SpringBoot 2.x整合MyBatis

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
简介: 用完spring-data-jpa之后并不是很想用mybatis,但是没办法呀,大环境还是mybatis,而且现在mybatis也出了不少插件,我们还是一起看看如何整合mybatis吧关于整合mybatis有两种方式,一种是注解方式,另一种是传统的xml方式注解方式先看看引入的依赖 org.

用完spring-data-jpa之后并不是很想用mybatis,但是没办法呀,大环境还是mybatis,而且现在mybatis也出了不少插件,我们还是一起看看如何整合mybatis吧
关于整合mybatis有两种方式,一种是注解方式,另一种是传统的xml方式

注解方式

先看看引入的依赖

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

sql文件

CREATE TABLE `test`.`Untitled`  (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  `passwd` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

application.properties

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql:///test?useSSL=true
spring.datasource.username=root
spring.datasource.password=root

#打印sql语句到控制台
logging.level.com.priv.gabriel.demoformybatis.mapper=debug

User.java

package com.priv.gabriel.demoformybatis.entity;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
public class User {

    private long id;

    private String username;

    private String passwd;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPasswd() {
        return passwd;
    }

    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
}

UserMapper.java

package com.priv.gabriel.demoformybatis.mapper;

import com.priv.gabriel.demoformybatis.entity.User;
import org.apache.ibatis.annotations.*;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
@Mapper
public interface UserMapper {

    /*注解方式的话直接在方法上写上对应的sql语句就可以了*/
    @Select("select * from user where id = #{id}")
    /*如果需要重复使用该Result,给该Results加一个 id 属性,下面即可使用@ResultMap(id)重复调用*/
    @Results(id = "user",value = {
            @Result(property = "username",column = "name")
    })
    User findById(long id);

    /*获取回传自增id*/
    /*id会自动存入user中*/
    @Insert("insert into user(name,passwd) values (#{username},#{passwd})")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    int inertUser(User user);
}

UserController.java

package com.priv.gabriel.demoformybatis.controller;

import com.priv.gabriel.demoformybatis.entity.User;
import com.priv.gabriel.demoformybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public User selectById(@PathVariable long id){
        return userMapper.findById(id);
    }

    @RequestMapping(value = {""},method = RequestMethod.POST)
    public String addUser(User user){
        userMapper.inertUser(user);
        return "现在自增id为"+user.getId();
    }
}

在SpringBoot1.x中还需要在启动类中加入@MapperScan("mapper所在目录"),而在2.x版本中不需要加入就可以自动扫描到mapper了

加入分页

需要引入pageHelper依赖

        <!-- 引入分页插件 -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>

在UserMapper中新增一个查询所有信息的方法

    @Select("select * from user")
    /*调用之前的Results*/
    @ResultMap("user")
    List<User> listUser();

在Controller中调用

    /*获取分页数据 包含分页详细信息*/
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public PageInfo getAll(@RequestParam Integer page, @RequestParam Integer size){
        PageHelper.startPage(page,size);
        List<User> users = userMapper.listUser();
        PageInfo<User> pageInfo = new PageInfo(users);
        return pageInfo;
    }

    /*仅获取分页数据
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public List<User> getAll(@RequestParam Integer page, @RequestParam Integer size){
        PageHelper.startPage(page,size);
        List<User> users = userMapper.listUser();
        return users;
    }*/

XML方式

xml方式的话和以前Spring整合mybatis没有太大的区别,在这里可以使用Mybatis-Generator自动生成代码少些一点代码,其余的话就不多介绍了

整合通用Mapper

不管是使用注解方式还是XML方式都还是会存在一个什么都得自己动手的情况,接下来的话,我们整合一个通用的Mapper,在mybatis中体验jpa的感觉
引用依赖

<!-- 引入通用mapper -->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.4</version>
        </dependency>

继承BaseMapper

package com.priv.gabriel.demoformybatis.mapper;


import com.priv.gabriel.demoformybatis.entity.User;
import org.apache.ibatis.annotations.Mapper;
import tk.mybatis.mapper.common.BaseMapper;

/**
 * Created with Intellij IDEA.
 *
 * @Author: Gabriel
 * @Date: 2018-10-14
 * @Description:
 */
@Mapper
public interface UserCommonMapper extends BaseMapper<User> {
}

接着在Controller中调用

   @Autowired
    private UserCommonMapper mapper;

    @RequestMapping("/testCommonMapperForSelectAll")
    public List<User> testCommonMapper(){
        return mapper.selectAll();
    }

关于mybatis的扩展很多,还有像mybatis-plus,关于这个话有时间再说吧,ε=ε=ε=┏(゜ロ゜;)┛

相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
29天前
|
前端开发 Java 关系型数据库
SpringBoot+MyBatis 天猫商城项目
SpringBoot+MyBatis 天猫商城项目
51 1
|
29天前
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
ssm(Spring+Spring mvc+mybatis)——updateDept.jsp
10 0
|
29天前
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
ssm(Spring+Spring mvc+mybatis)——showDept.jsp
9 0
|
28天前
|
SQL Java 数据库连接
springboot中配置mybatis别名该怎么写?
springboot中配置mybatis别名该怎么写?
22 0
|
1月前
|
XML Java 关系型数据库
【SpringBoot系列】SpringBoot集成Fast Mybatis
【SpringBoot系列】SpringBoot集成Fast Mybatis
|
28天前
|
SQL JavaScript Java
springboot+springm vc+mybatis实现增删改查案例!
springboot+springm vc+mybatis实现增删改查案例!
23 0
|
28天前
|
SQL Java 数据库连接
挺详细的spring+springmvc+mybatis配置整合|含源代码
挺详细的spring+springmvc+mybatis配置整合|含源代码
35 1
|
1月前
|
druid Java 数据库连接
Spring Boot3整合MyBatis Plus
Spring Boot3整合MyBatis Plus
39 1
|
9天前
|
SQL Java 数据库连接
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
【mybatis】第一篇,Springboot中使用插件PageHelper不生效解决方案
|
21天前
|
JavaScript Java 关系型数据库
SpringBoot + Mybatis + Vue的代码生成器
SpringBoot + Mybatis + Vue的代码生成器
32 2

热门文章

最新文章