SpringBoot(2.1.9.RELEASE)集成MyBatis

Posted wessonshin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot(2.1.9.RELEASE)集成MyBatis相关的知识,希望对你有一定的参考价值。

  这篇文章主要讲解SpringBoot集成MyBatis实现一个最基本的增删改查功能,并连接访问数据库。整合之前你需要随便准备一个数据表就行。SpringBoot集成MyBatis非常简单,不需要Spring繁琐的配置,也不需要配置类就能够快速集成。

 

准备数据

技术图片
create table `user_table` (
   `user_id` int (11),
   `nickname` varchar (60),
   `password` varchar (150),
   `gender` char (3),
   `security_email` varchar (150),
   `mobile_phone` varchar (33),
   `account_balance` double 
); 
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(1,曾小贤,xiange123456,,xiaoxian@163.com,12138,520000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(2,胡一菲,yifei123456,,yifei@163.com,12138,450000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(3,关谷神奇,qiefuzijin,,guangu@163.com,12138,190000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(4,吕子乔,lvbu123456,,lvbu@163.com,12138,10000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(5,陈美嘉,meijia123456,,meijia@163.com,12138,25000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(6,陆展博,zhanbo123456,,zhanbo@163.com,12138,250000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(7,林宛瑜,wanyu666666,,wanyu@163.com,12138,66000000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(8,唐悠悠,uu123456,,tanguu@163.com,12138,150000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(9,张伟,snake123456,,weige@163.com,12138,80000);
insert into `user_table` (`user_id`, `nickname`, `password`, `gender`, `security_email`, `mobile_phone`, `account_balance`) values(10,秦羽墨,yumo123456,,yumo@163.com,12138,200000);
View Code

整合完成后显示项目的整体目录结构如下:

技术图片

 

1.build.gradle项目依赖

创建gradle模块springboot-mybatis并添加如下依赖,至于各自是什么意思,自己去 Maven 仓库官网去查,你们懂得!

dependencies {
    compile group: ‘org.projectlombok‘, name: ‘lombok‘, version: ‘1.18.10‘
    compile group: ‘com.alibaba‘, name: ‘druid‘, version: ‘1.1.20‘
    compile group: mysql‘, name: ‘mysql-connector-java‘, version: ‘8.0.12‘
    compile group: ‘org.springframework.boot‘, name: ‘spring-boot-starter-web‘
    compile group: ‘org.mybatis.spring.boot‘, name: ‘mybatis-spring-boot-starter‘, version: ‘2.1.0‘
}

2.application.yaml配置文件

Yaml配置文件中需要配置数据源四大要素、数据源类型,MyBatis需要配置SQL映射文件类路径位置、搜索类型别名实体类包以及MyBatis控制台输出SQL日志。

技术图片
server:
  port: 8080
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/user?characterEncoding=utf8&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
mybatis:
  mapper-locations:
    - classpath:mapper/*.xml
  type-aliases-package: org.wesson.springboot.mybatis.entity
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
View Code

3.启动类SpringbootMybatisApplication.java

技术图片
package org.wesson.springboot.mybatis;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("org.wesson.springboot.mybatis.dao") // 扫描Mybatis的数据访问层接口
public class SpringbootMybatisApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMybatisApplication.class, args);
    }

}
View Code

4.实体类UserTable.java

  至于为什么我没有写省略getter与setter方法,是因为在上述build.gradle文件中引入了lombok依赖,在使用lombok之前你还需要在IDEA中下载lombok插件。通过使用@Data注解能够自动生成getter,setter,equals,hashCode和toString方法!

技术图片
package org.wesson.springboot.mybatis.entity;

import lombok.Data;

import java.io.Serializable;

@Data
public class UserTable implements Serializable {
    private static final long serialVersionUID = 368351536604804313L;
    /**
    * 用户id
    */
    private Integer userId;
    /**
    * 账号昵称
    */
    private String nickname;
    /**
    * 账号密码
    */
    private String password;
    /**
    * 性别
    */
    private Character gender;
    /**
    * 安全邮箱
    */
    private String securityEmail;
    /**
    * 手机号码
    */
    private String mobilePhone;
    /**
    * 账户余额
    */
    private Double accountBalance;
}
View Code

5.数据访问层接口UserTableDao.java

技术图片
package org.wesson.springboot.mybatis.dao;

import org.springframework.stereotype.Repository;
import org.wesson.springboot.mybatis.entity.UserTable;
import org.apache.ibatis.annotations.Param;
import java.util.List;

@Repository
public interface UserTableDao {

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    UserTable queryById(Integer userId);

    /**
     * 查询指定行数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    List<UserTable> queryAllByLimit(@Param("offset") int offset, @Param("limit") int limit);


    /**
     * 通过实体作为筛选条件查询
     *
     * @param userTable 实例对象
     * @return 对象列表
     */
    List<UserTable> queryAll(UserTable userTable);

    /**
     * 新增数据
     *
     * @param userTable 实例对象
     * @return 影响行数
     */
    int insert(UserTable userTable);

    /**
     * 修改数据
     *
     * @param userTable 实例对象
     * @return 影响行数
     */
    int update(UserTable userTable);

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 影响行数
     */
    int deleteById(Integer userId);

}
View Code

6.SQL映射文件UserTableDao.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="org.wesson.springboot.mybatis.dao.UserTableDao">

    <resultMap type="org.wesson.springboot.mybatis.entity.UserTable" id="UserTableMap">
        <result property="userId" column="user_id" jdbcType="INTEGER"/>
        <result property="nickname" column="nickname" jdbcType="VARCHAR"/>
        <result property="password" column="password" jdbcType="VARCHAR"/>
        <result property="gender" column="gender" jdbcType="OTHER"/>
        <result property="securityEmail" column="security_email" jdbcType="VARCHAR"/>
        <result property="mobilePhone" column="mobile_phone" jdbcType="VARCHAR"/>
        <result property="accountBalance" column="account_balance" jdbcType="NUMERIC"/>
    </resultMap>

    <!--查询单个-->
    <select id="queryById" resultMap="UserTableMap">
        select
          user_id, nickname, password, gender, security_email, mobile_phone, account_balance
        from user.user_table
        where user_id = #{userId}
    </select>

    <!--查询指定行数据-->
    <select id="queryAllByLimit" resultMap="UserTableMap">
        select
          user_id, nickname, password, gender, security_email, mobile_phone, account_balance
        from user.user_table
        limit #{offset}, #{limit}
    </select>

    <!--通过实体作为筛选条件查询-->
    <select id="queryAll" resultMap="UserTableMap">
        select
          user_id, nickname, password, gender, security_email, mobile_phone, account_balance
        from user.user_table
        <where>
            <if test="userId != null">
                and user_id = #{userId}
            </if>
            <if test="nickname != null and nickname != ‘‘">
                and nickname = #{nickname}
            </if>
            <if test="password != null and password != ‘‘">
                and password = #{password}
            </if>
            <if test="gender != null">
                and gender = #{gender}
            </if>
            <if test="securityEmail != null and securityEmail != ‘‘">
                and security_email = #{securityEmail}
            </if>
            <if test="mobilePhone != null and mobilePhone != ‘‘">
                and mobile_phone = #{mobilePhone}
            </if>
            <if test="accountBalance != null">
                and account_balance = #{accountBalance}
            </if>
        </where>
    </select>

    <!--新增所有列-->
    <insert id="insert" keyProperty="userId" useGeneratedKeys="true">
        insert into user.user_table(nickname, password, gender, security_email, mobile_phone, account_balance)
        values (#{nickname}, #{password}, #{gender}, #{securityEmail}, #{mobilePhone}, #{accountBalance})
    </insert>

    <!--通过主键修改数据-->
    <update id="update">
        update user.user_table
        <set>
            <if test="nickname != null and nickname != ‘‘">
                nickname = #{nickname},
            </if>
            <if test="password != null and password != ‘‘">
                password = #{password},
            </if>
            <if test="gender != null">
                gender = #{gender},
            </if>
            <if test="securityEmail != null and securityEmail != ‘‘">
                security_email = #{securityEmail},
            </if>
            <if test="mobilePhone != null and mobilePhone != ‘‘">
                mobile_phone = #{mobilePhone},
            </if>
            <if test="accountBalance != null">
                account_balance = #{accountBalance},
            </if>
        </set>
        where user_id = #{userId}
    </update>

    <!--通过主键删除-->
    <delete id="deleteById">
        delete from user.user_table where user_id = #{userId}
    </delete>

</mapper>
View Code

7.业务逻辑层接口UserTableService.java

技术图片
package org.wesson.springboot.mybatis.service;

import org.wesson.springboot.mybatis.entity.UserTable;
import java.util.List;

public interface UserTableService {

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    UserTable queryById(Integer userId);

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    List<UserTable> queryAllByLimit(int offset, int limit);

    /**
     * 新增数据
     *
     * @param userTable 实例对象
     * @return 实例对象
     */
    UserTable insert(UserTable userTable);

    /**
     * 修改数据
     *
     * @param userTable 实例对象
     * @return 实例对象
     */
    UserTable update(UserTable userTable);

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    boolean deleteById(Integer userId);

}
View Code

8.业务逻辑层实现类UserTableServiceImpl.java

技术图片
package org.wesson.springboot.mybatis.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.wesson.springboot.mybatis.entity.UserTable;
import org.wesson.springboot.mybatis.dao.UserTableDao;
import org.wesson.springboot.mybatis.service.UserTableService;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserTableServiceImpl implements UserTableService {
    @Autowired
    private UserTableDao userTableDao;

    /**
     * 通过ID查询单条数据
     *
     * @param userId 主键
     * @return 实例对象
     */
    @Override
    public UserTable queryById(Integer userId) {
        return this.userTableDao.queryById(userId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<UserTable> queryAllByLimit(int offset, int limit) {
        return this.userTableDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param userTable 实例对象
     * @return 实例对象
     */
    @Override
    public UserTable insert(UserTable userTable) {
        this.userTableDao.insert(userTable);
        return userTable;
    }

    /**
     * 修改数据
     *
     * @param userTable 实例对象
     * @return 实例对象
     */
    @Override
    public UserTable update(UserTable userTable) {
        this.userTableDao.update(userTable);
        return this.queryById(userTable.getUserId());
    }

    /**
     * 通过主键删除数据
     *
     * @param userId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer userId) {
        return this.userTableDao.deleteById(userId) > 0;
    }
}
View Code

9.控制层UserTableController.java

Controller这里只演示一个通过ID查询单条数据的Restful接口,至于其它的,自己去练习吧!今天重点是SpringBoot集成MyBatis。

技术图片
package org.wesson.springboot.mybatis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.wesson.springboot.mybatis.entity.UserTable;
import org.wesson.springboot.mybatis.service.UserTableService;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/userTable")
public class UserTableController {
    /**
     * 服务对象
     */
    @Autowired
    private UserTableService userTableService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("/selectOne")
    public UserTable selectOne(Integer id) {
        return this.userTableService.queryById(id);
    }

}
View Code

10.测试查询数据

运行 SpringbootMybatisApplication.java 启动类,浏览器访问 http://localhost:8080/userTable/selectOne?id=1 请求,输出结果如下:

技术图片

其实我并没有写任何关于增删改查的代码,我在IDEA中使用了另一个插件叫easycode,easycode能够为你自动生成entity.java、dao.java、service.java、serviceImpl.java、controller.java和mapper.xml简单的业务代码。至于复杂的业务逻辑,还是需要自己手写的!!!

以上是关于SpringBoot(2.1.9.RELEASE)集成MyBatis的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot 2.x版本+MultipartFile设置指定文件上传大小

SpringBoot无法访问webapp目录下的文件

Maven 编译提示:spring-boot-maven-plugin:2.1.9.RELEASE or one of its dependencies could not be resolved

SpringCloud找不到@HystrixCommand标签

Spring Boot + Oauth 2单点登录ridirect uri错误行为

报错spring实战(第四版)示例代码 ,使用 @DeclareParents 实现aop出错