springboot(2.1.9.release)集成mybatis

wessonshin      2022-05-03     313

关键词:

  这篇文章主要讲解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简单的业务代码。至于复杂的业务逻辑,还是需要自己手写的!!!

Spring Boot + Oauth2 单点登录重定向 uri 错误行为

】SpringBoot+Oauth2单点登录重定向uri错误行为【英文标题】:SpringBoot+Oauth2SingleSign-Onridirecturimisbehaviour【发布时间】:2020-09-0104:53:54【问题描述】:我需要使用SpringBoot(2.1.9.RELEASE)和OAuth2实现单点登录应用程序。我还创建了两个客户... 查看详情

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

来源:spring实战(第四版)章节:4.3.4通过注解引入新功能页码:P120环境:springboot  2.1.9.RELEASE报错信息:warningcan‘tdetermineimplementedinterfacesofmissingtypeorg.springframework.boot.autoconfigure.jdbc.metadata.DataSourc 查看详情

zuul2.x网关实现服务熔断降级(代码片段)

版本:<properties><spring-boot.version>2.1.9.RELEASE</spring-boot.version><spring-cloud.version>Greenwich.SR4</spring-cloud.version></properties>所需依赖:  <properties><spring-cloud.version>Greenwich.SR4</spring-cloud.version></pr... 查看详情

自定义ossstarter(代码片段)

软件架构基于spring-boot2.1.9.RELEASE、阿里云aliyun-sdk-oss3.7.0<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version> 查看详情

springboot.06.springboot日志管理

SpringBoot.06.SpringBoot日志管理SpringBoot日志介绍概念日志的级别日志的分类SpringBoot日志基本使用1.新建Module2.项目配置3.配置日志SpringBoot日志切割1.application.yml2.application-dev.yml3.logback-dev.xml4.测试SpringBoot日志介绍概念在SpringBoot框架中... 查看详情

springboot

参考:http://www.ityouknow.com/springboot(一):入门篇springboot(二):web综合开发springboot(三):SpringBoot中Redis的使用springboot(四):thymeleaf使用详解springboot(五):springdatajpa的使用springboot(六):如何优雅的使用mybatisspringboot(七):sp 查看详情

springboot系列

https://my.oschina.net/xiedeshou?tab=newest&catalogId=5936801SpringBoot|第零章:前言SpringBoot|第一章:第一个SpringBoot应用SpringBoot|第二章:lombok介绍及简单使用SpringBoot|第三章:springboot配置详解SpringBoot|第四章:日志配置SpringBoot|第 查看详情

springboot学习——springboot简介

    最近工作中需要使用到SpringBoot,但是以前工作中没有用到过SpringBoot,所以需要学习下SpringBoot。本系列笔记是笔者学习SpringBoot的笔记,有错误和不足之处,请不吝指教。    话不多说,直接进入... 查看详情

springboot制作个人博客目录

前端框架构建SpringBoot制作个人博客-首页SpringBoot制作个人博客-详情页SpringBoot制作个人博客-分类页SpringBoot制作个人博客-标签页SpringBoot制作个人博客-归档页SpringBoot制作个人博客-关于我页SpringBoot制作个人博客-博客管理列表页Spri... 查看详情

springboot.06.springboot日志管理(代码片段)

SpringBoot.06.SpringBoot日志管理SpringBoot日志介绍概念日志的级别日志的分类SpringBoot日志基本使用1.新建Module2.项目配置3.配置日志SpringBoot日志切割1.application.yml2.application-dev.yml3.logback-dev.xml4.测试SpringBoot日志介绍概念在SpringBoot框架中... 查看详情

springboot.06.springboot日志管理(代码片段)

SpringBoot.06.SpringBoot日志管理SpringBoot日志介绍概念日志的级别日志的分类SpringBoot日志基本使用1.新建Module2.项目配置3.配置日志SpringBoot日志切割1.application.yml2.application-dev.yml3.logback-dev.xml4.测试SpringBoot日志介绍概念在SpringBoot框架中... 查看详情

springboot报错,springboot注解

目录SpringBoot注解SpringBoot注解一、注解(annotations)列表@SpringBootApplication:?包含了@ComponentScan、@Configuration和@EnableAutoConfiguration注解。其中@ComponentScan让SpringBoot扫描到Configuration类并把它加入到程序上下文。@Configuration: 查看详情

springboot微服务框架概述

SpringBoot微服务框架2.SpringBoot微服务框架的特点3.SpringBoot应用场景4.SpringBoot的第一个应用5.Springboot引导类的main方法有什么作用?6.SpringBoot的场景启动器7.@SpringBootApplication探究8.如何配置SpringBoot的配置文件?1.SpringBoot概述SpringBoot是... 查看详情

springboot介绍

SpringBoot集成教程SpringBoot介绍SpringBoot开发环境搭建(Eclipse)SpringBootHelloWorld(restful接口)例子springboot连接Mysqlspringboot配置druid连接池连接mysqlspringboot集成mybatis(1)springboot集成mybatis(2)–使用pagehelper实现分页springboot集 查看详情

springboot源码分析----springboot自动配置

前言springboot项目将模块化设计发挥到及至,需要什么模块,只需导入这个模块对应的stater即可,当然,用户根据业务需要自定义相关的stater,关于自定义stater在后续章节将一一解说,学习springboot,首要了解springboot的自动配置原... 查看详情

springboot

目录  简介  application.properties  Maven搭建SpringBoot  SpringBoot&Thymeleaf  ErrorPageIDE搭建SpringBoot简介SpringBoot是微服务框架,SpringBoot框架,它的作用很简单,就是帮我们自动配置。SpringBoot框架的核心就是自动配置,只要... 查看详情

springboot入门到精通-springboot集成ssm开发项目(代码片段)

SpringBoot入门到精通系列SpringBoot入门到精通-Spring的注解编程(一)SpringBoot入门到精通-SpringBoot入门(二)SpringBoot入门到精通-Spring的基本使用(三)SpringBoot入门到精通-SpringBoot集成SSM(四)前言上一篇文章我们讲的是SpringBoot的基本用法,... 查看详情

springboot制作个人博客目录

前端框架构建SpringBoot制作个人博客-首页SpringBoot制作个人博客-详情页SpringBoot制作个人博客-分类页SpringBoot制作个人博客-标签页SpringBoot制作个人博客-归档页SpringBoot制作个人博客-关于我页SpringBoot制作个人博客-博客管理列表页Spri... 查看详情