Spring boot mybatis

Spring Boot与MyBatis Spring Boot是一个用于创建独立的、基于Spring的生产级应用程序的框架,它简化了Spring应用的初始搭建以及开发过程。MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。将Spring Boot和MyBatis结合使用,可以高效地开发数据驱动的应用程序。 阅读详情

上一节 spring boot test

spring boot test

源码


Spring boot mybatis

springboot 整合 mybatis

mybatis 简介

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

springboot 整合mybatis

  • 添加依赖
    添加驱动和 mybatis-spring-boot-starter
      <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>2.1.3</version>
       </dependency>
       <dependency>
           <groupId>mysql</groupId>
           <artifactId>mysql-connector-java</artifactId>
           <version>5.1.47</version>
       </dependency>
  • 配置文件
    配置数据源
    spring:
      application:
        name: mybatis-demo
      datasource:
        url: jdbc:mysql://localhost:3306/mytest?useSSL=false&charsetEncoding=utf8
        username: root
        password: 123456
        driver-class-name: com.mysql.jdbc.Driver
    
    配置mabatis相关配置
    mybatis:
       # 配置 mybatis 的configuration 文件位置
     #  config-location: classpath:mybatis/mybatis-config.xml
       # 配置 mapper 文件的位置
       mapper-locations: classpath:mybatis/mapper/*
       # 配置别名, 默认是类名首字母小写;也可以使用@Alias
       type-aliases-package: com.xiaodu.mybatis.entity
       # configuration 配置 config-location 和 configuration 不能同时配置
       configuration:
         # 下划线转大写映射实体类字段
         map-underscore-to-camel-case: true
    

mybatis 配置官方详解: https://mybatis.org/mybatis-3/zh/configuration.html#
创建数据库表

drop table t_user;
commit;
create table t_user
(
    u_id        varchar(64)                         not null
        primary key,
    u_name      varchar(32)                         not null,
    password    varchar(32)                         not null,
    money       int(10)                             null,
    create_time timestamp default CURRENT_TIMESTAMP not null
);
commit ;
代码示例
创建mapper
@Mapper 为mybatis 注解,标注为映射器,加入到springbean管理中;@Repository 是spring 带的注解,也可以不加,这里是为了 不让idea 使用@Autowired 的时候报红(如下),当然你也可以设置告警级别。
在这里插入图片描述
创建mapper
@Mapper
@Repository
public interface UserMapper {

    UserEntity getOne(String id);


}
创建mapper对应的xml文件
我们已经在配置文件中通过 mapper-locations: classpath:mybatis/mapper/* 指定了 mapper.xml文件的地址;
所以我们需要在该路径下创建对应的mapper.xml文件

创建userMapper.xml,并创建对应的select语句

<?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="com.xiaodu.mybatis.mapper.UserMapper">
    <select id="getOne" resultType="userEntity">
        select u_id, u_name, password, money, create_time from t_user where u_id = #{uId}
    </select>
</mapper>
service和controller
模拟下正常开发下的场景,我们创建对应的service 和controller

service

public interface UserService {

    UserEntity oneUser(String id) throws Exception;

    List<UserEntity> listUser(List<String> ids) throws Exception;

    List<UserEntity> listUser(UserEntity userEntity) throws Exception;

    int addUser(UserEntity userEntity) throws Exception;

    int batchUser(List<UserEntity> users)throws Exception;

    int delUser(String id) throws Exception;

    int updateUser(UserEntity userEntity) throws Exception;
}
...
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserEntity oneUser(String id) throws Exception {
        return userMapper.getOne(id);
    }

    //todo
    @Override
    public List<UserEntity> listUser(List<String> ids) throws Exception {
        return null;
    }
    //todo
    @Override
    public List<UserEntity> listUser(UserEntity userEntity) throws Exception {
        return null;
    }
    //todo
    @Override
    public int addUser(UserEntity userEntity) throws Exception {
        return 0;
    }
    //todo
    @Override
    public int batchUser(List<UserEntity> users) throws Exception {
        return 0;
    }
    //todo
    @Override
    public int delUser(String id) throws Exception {
        return 0;
    }
    //todo
    @Override
    public int updateUser(UserEntity userEntity) throws Exception {
        return 0;
    }
}

controller

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public UserEntity getUserOne(@RequestParam String id) throws Exception {
        return userService.oneUser(id);

    }

}

数据库映射实体; @Alias 指定了别名,我们在配置文件中也做了全局配置 type-aliases-package: com.xiaodu.mybatis.entity; 也可以不加,不过不加有的时候在xml文件 中 使用resultType=“userEntity” 会爆红

@ToString
@Alias("userEntity")
public class UserEntity {

    private String uId;

    private String uName;

    private String password;

    private Long money;

    private Date createTime;

    public String getuId() {
        return uId;
    }

    public void setuId(String uId) {
        this.uId = uId;
    }

    public String getuName() {
        return uName;
    }

    public void setuName(String uName) {
        this.uName = uName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Long getMoney() {
        return money;
    }

    public void setMoney(Long money) {
        this.money = money;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }
}

这样一个完整的使用示例就完成了, 可以正常访问查询数据;

注解版使用介绍

注解版适用简单sql, 复杂sql使用注解很不美观和方便。
@Select
@Delete
@Update
@Insert

简单以其中几个为 代码示例

  • select
  @Select("select * from t_user where u_id = #{id}")
  • update
   @Update("update t_user set password = #{password}, money = #{money}, create_time = #{createTime} where u_id = #{uId}")
    int updateUser(UserEntity userEntity);
  • 注解中使用动态sql
    @Select("<script>" +
            "  select * from t_user \n" +
            "        <where>\n" +
            "            u_id in\n" +
            "            <foreach collection=\"list\" item=\"id\" open=\"(\" close=\")\" separator=\",\">\n" +
            "                #{id}\n" +
            "            </foreach>\n" +
            "        </where>\n"+
                   "</script>")
    List<UserEntity> listUser(List<String> ids);

注解中使用动态sql,感觉没有在xml中使用方便,1. 没有自动提示,容易写错,我一般都是在xml中写好 复制过来 2. 不美观,代码太乱。

结果映射
@Results
@Result
@ResultMap
@ResultType

使用示例

@results

 @Select("select * from t_user where u_id = #{id}")
    @Results(id = "userResultMap2", value = {
            @Result(column = "u_name", property = "uName"),
            @Result(column = "u_id", property = "uId"),
            @Result(column = "money", property = "money"),
            @Result(column = "create_time", property = "createTime")
    })
    UserEntity selectOne(String id);

@resultMap
ResultMap 可以指定xml文件中的 resultMap 也可以指定 @Results 的id

    @Select("select * from t_user where u_id = #{id}")
    @ResultMap("userResultMap")
//    @ResultMap("userResultMap2")
    UserEntity selectById(String id);
sql生成器

@DeleteProvider
@SelectProvider
@InsertProvider
@UpdateProvider
以 @DeleteProvider 为代码示例,其他使用方法是一样的; value 指定代码 生成sql的类sqlProvider, 通过method 指定那个方法生成;
若只有一个参数则直接传参就行,多个参数使用map接收

    @DeleteProvider(value = UserProvider.class, method = "delUser")
     int deleteUser(String id);
public class UserProvider {

    public String delUser(String id) {

        return "delete from t_user where u_id = '" + id+ "'";
    }
}

以上只是简单示例,详细请网上查阅。

其他

mybatis分页
mybatis 自带分页

mybatis 使用 rowBounds 进行分页,是逻辑逻辑分页,先全部查询出来,然后再内存中进行分页截取相关数据返回,所以一般
情况下不使用这种分页,只做了解

代码示例

//mapper  我们接收一个rowBounds
     @Select("select * from t_user")
    List<UserEntity> selectAll(RowBounds rowBounds);
    ...
// 
    @Override
    public List<UserEntity> pageUser(Integer pageNo, Integer pageSize) {
        pageNo = pageNo <= 0 ? 1 : pageNo;
        pageSize = pageSize <= 0 ? 5 : pageSize;
        RowBounds rowBounds = new RowBounds((pageNo -1) * pageSize, pageSize);
        return userMapper.selectAll(rowBounds);
    }
pageHelper 分页

pageHelper-gitHub

通常我们会使用第三方框架进行分页,例如 使用 pageHelper 进行分页;这里只是简单示例,
更详细的请查询官网。
添加依赖

   <dependency>
           <groupId>com.github.pagehelper</groupId>
           <artifactId>pagehelper-spring-boot-starter</artifactId>
           <version>1.2.10</version>
       </dependency>

代码示例
使用 PageHelper.startPage 进行分页

    public PageInfo<UserEntity> pageHelperUser(Integer pageNo, Integer pageSize) {
        pageNo = pageNo <= 0 ? 1 : pageNo;
        pageSize = pageSize <= 0 ? 5 : pageSize;
        return PageHelper.startPage(pageNo, pageSize).doSelectPageInfo(() -> userMapper.selectUserAll());
    }
    

若加入了 pageHelper ,mybatis自带的rowBounds 分页也会拦截 进行物理分页,所以 使用rowBounds 也能进行物理分页了。

mybatis拦截器

分页插件 PageHelper 是使用的mybatis 提供的拦截器进行分页, 分页拦截器 PageInterceptor;

我们这里模拟使用mybatis 拦截器进行 字段 updateTime 和createTime 的赋值。
1. 创建拦截器
使用@Intercepts 声明为拦截器, @Signature 具体拦截哪些类的那些方法

@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class DateInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType(); 
        Object arg = args[1];
        Executor executor = (Executor) invocation.getTarget();
        Field createTime = ReflectionUtils.findField(arg.getClass(), "createTime");
        Field updateTime = ReflectionUtils.findField(arg.getClass(), "updateTime");
        if (createTime != null && sqlCommandType.equals(SqlCommandType.INSERT)) {
            fieldSet(arg, createTime);
        }

        if (updateTime != null && sqlCommandType.equals(SqlCommandType.UPDATE)) {
            fieldSet(arg, updateTime);
        }
        return executor.update(mappedStatement, arg);
    }

    private void fieldSet(Object arg, Field f) {
        ReflectionUtils.makeAccessible(f);
        Class<?> type = f.getType();
        if (type == Date.class) {
            ReflectionUtils.setField(f, arg, new Date());
        } else if (type == java.sql.Date.class) {
            ReflectionUtils.setField(f, arg, new java.sql.Timestamp(new Date().getTime()));

        } else if (type == LocalDateTime.class) {
            ReflectionUtils.setField(f, arg, LocalDateTime.now());
        } else if (type == LocalDate.class) {
            ReflectionUtils.setField(f, arg, LocalDate.now());
        }
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}

2. 添加拦截器到mybatis中

@Configuration
public class MybatisConfig {

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.addInterceptor(new DateInterceptor());
    }
}

由于我们拦截的是 Executor 的 update 方法; 当执行 insert , update ,delete 命令时 就会走该拦截器,
再拦截器代码中 我们约定 实体bean的属性为 createTime 和 updateTime;我们动态的判断sql命令
给 属性赋值。

总结: 以上是 springboot 整合mybatis 后的简单使用;单个知识点还请自行查询。


下一节 spring boot jpa

springboot jpa

spring-boot(整合mybatis) 每天发给人机看,我拿csdn当笔记本 阅读详情

相关推荐

深入解析Zynq Ultrascale+ RF Data Converter中的PLL配置与时钟管理

本文深入解析了Zynq Ultrascale+ RF Data Converter中PLL配置与时钟管理的核心原理与实践。文章将RFDC时钟系统比作交响乐团,详细阐述了PLL作为指挥的关键作用,以及系统时钟、Tile时钟、参考时钟与采样时钟的层级关系。重点剖析了PLL配置参数(如VCO频率、分频器设置)的计算方法与稳定性考量,并提供了从IP配置使能顺序到多Tile同步、DRP访问等常见问题的实战避坑指南与调试技巧,帮助工程师构建稳定的射频信号处理基石。

7up55的博客 449

SpringBoot集成mybatis拦截器的实现

①创建SpringBoot工程 项目目录: ②导入jar包 <!--SpringBoot与mybatis的整合--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starte...

Wall的博客 9462

玩转openclaw+企业微信

OpenClaw横空出世:AI从问答到执行的范式革命 OpenClaw作为2026年AI领域的重大突破,实现了从对话机器人到智能执行体的进化。其核心价值在于"自主执行"而非简单交互,通过六层解耦架构(表现层、网关层、运行时层、技能层、工具层、记忆层)构建完整执行闭环。关键技术包括Model Context Protocol实现多模型兼容,以及事件驱动架构确保实时响应。安装过程支持多平台,通过Node.js环境即可快速部署,并支持对接主流大模型。OpenClaw标志着AI开始真正&quot

西木风落 1590

SpringBoot系列(四)整合Mybatis实现拦截

自动实现数据库时间字段的添加

北堂飘霜_记录 1229

WPS文档中心和文档中台 operate 未授权访问漏洞(CVE-2025-0717)

WPS文档中心和文档中台的/open/v6/api/etcd/operate?key=/config/storage&method=get接口存在未授权访问漏洞,攻击者可通过该漏洞获取AK/SK密钥等信息,这些密钥通常用于系统内部认证和权限控制,泄露后可能导致攻击者进一步修改K8s配置、部署恶意容器或执行远程命令,最终实现对系统的完全控制。

李同學AI安全 902

TPAMI 2025 | 从缺失碎片到杰作:基于上下文自适应扩散的图像修复

图像修复是一项具有挑战性的任务,尤其是要确保生成的内容与图像的现有部分无缝融合。尽管最近的扩散模型展现出了潜力,但它们在保持已知区域和未知(缺失)区域之间的连贯性方面常常遇到困难。这个问题源于扩散过程中缺乏明确的空间和语义对齐,导致生成的内容无法与原始图像平滑融合。此外,扩散模型通常依赖全局学习分布,而非局部特征,这使得生成的图像部分与现有图像部分之间存在不一致。在这项工作中,作者提出了ConFill,这是一个新颖的框架,引入了上下文自适应差异(CAD)模型,以确保在整个扩散过程中,已知区域和未知区域的中间

小白学视觉 239

spring boot mybatis拦截器

mybaits拦截器 package com.chinamobile.scm.masterdata.interceptor; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.executor.Executor; import org.apache.iba...

杨航的专栏 4456

海康威视iVMS-8700综合安防管理平台 文件读取漏洞复现

HIKVISION iVMS 综合安防管理平台download接口处存在任意文件读取漏洞,攻击者通过构造token绕过身份认证,读取服务器中的目录信息与敏感文件。使系统处于极不安全的状态。

0xSec 3304

[ Spring ] Spring Boot Mybatis++ 2025

[ Spring ] Spring Boot Mybatis++ 2025

天天向上 Up Up Up (*^▽^*) 3536

基于学术研究于NASA官网GPM卫星数据下载详细教程

基于学术研究于NASA官网GPM卫星数据下载详细教程

珞瑜的博客 8654

把数据库事务边界握在手里:ABAP 里的 COMMIT CONNECTION 与 ROLLBACK CONNECTION 深度拆解

与表面是两条很短的语句,背后却牵动了连接管理、数据库 LUW、SAP LUW、隐式提交、游标生命周期、GTT 平台差异等一整片工程现实。把它们用对,你就能在不破坏主业务事务的前提下,实现跨库写入、审计落库、隔离型日志、数据集成落地等一系列“看似矛盾”的目标;用错了,它们也会悄无声息地制造一致性缺口,让问题在高峰期以 dump 或数据异常的方式爆出来。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 1836

Spring Boot整合MyBatis

在开发中,通常会涉及到对数据库的数据进行操作,Spring Boot在简化项目开发以及实现自动化配置的基础上,对关系型数据库和非关系型数据库的访问操作都提供了非常好的整合支持。Spring Boot默认采用整合SpringData的方式统一处理数据访问层,通过添加大量自动配置,引入各种数据访问模板xxxTemplate以及统一的Repository接口,从而达到简化数据访问层的操作。Spring Boot提供的常见数据库依赖启动器名称对应数据库。

梁辰兴的博客 1万+

YOLO26涨点改进 | 独家创新,特殊场景检测篇 | TGRS 2025 | 引入FAENet特征自适应增强网络,专注于恶劣天气条件下的目标检测(低光场景、雾天场景、雨雪场景、复杂环境等)即插即用

🔥本文提出了一种名为FAENet的特征自适应增强网络,可有效提升YOLO26在恶劣天气条件下的目标检测性能。FAENet通过拉普拉斯金字塔分解思想,将输入特征分为低频和高频两部分进行针对性增强:低频分支强化全局轮廓,高频分支增强边缘纹理细节。该模块设计轻量、可端到端训练,在不改变原始图像分布的前提下,显著缓解雾霾、低照度等复杂环境造成的特征退化问题。实验表明,该方法在多个恶劣天气数据集上超越了当前最优检测器,同时保持了轻量级和高速度特性。

Ai缝合怪、助力小伙伴高效发论文 332

spring boot+mybatis开发基础复习

spring boot+mybatis复习

2201_75999403的博客 962

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

android 蓝牙通讯demo

android 下蓝牙通讯demo,实现了发现蓝牙,使能蓝牙,通过蓝牙发送消息。

Spring Boot 集成 mybatis 浅析

SpringBoot是对Spring框架的封装增强,通过Starter依赖管理和自动配置机制简化开发。它提供spring-boot-starter-*依赖包自动管理兼容版本,利用@EnableAutoConfiguration基于条件注解实现零配置启动。核心仍为Spring Framework,默认集成SpringMVC但支持多种应用类型。自动配置通过扫描classpath组件实现,开发者也可手动集成非官方模块。相比传统Spring,SpringBoot显著减少了配置工作量,使开发者能快速构建生产级应用。

chxii的专栏 1219

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

Spring Boot整合MyBatis实现简单的CRUD

这篇文章主要针对java初学者,详细介绍如何创建一个基本的springboot项目来对数据库进行crud操作。

沐雨橙风ιε的博客 4486

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

Spring Boot 集成 MyBatis 全面讲解

ResultMap用于自定义数据库字段与 Java 对象属性的映射。它支持嵌套映射、别名和字段处理,适合复杂的对象映射场景。SqlSessionMapper配置文件和ResultMap是 MyBatis 的核心概念。通过灵活的配置和映射,MyBatis 可以高效地处理各种复杂的数据库操作需求。熟练掌握这些特性可以让开发者在项目中更高效地处理数据访问逻辑。三、Spring Boot 集成 MyBatisMyBatis 是一种轻量级的持久层框架,与 Spring Boot 集成后可以极大地提升开发效率。

旺旺小崔崔的博客 2235

【Spring Boot】基于MyBatis的条件分页

条件分页是平常工作生产中十分常见的场景。储存过程还流行的年代,喜欢把分页逻辑封装在储存过程里,称之为数据库分页。甚至在前端,我们也可以通过对Array的操作实现前端分页。 本篇文章主要还是在Spring Boot框架上基于MyBatis来实现分页,并且引申出诸如分页数据封装对象,PageHelpe辅助工具和MyBatis XML中实现条件语句这些工作中实用的点,希望能帮助到大家。

Arabys的博客 1161

Spring Boot整合tk-mybatis、PageHelper

本文介绍了tk-mybatis这一曾经流行的MyBatis增强框架的使用方法,尽管它已被MyBatis-Plus取代,但仍值得了解。文章详细展示了如何从零开始整合tk-mybatis:从数据库准备(创建歌曲表并插入测试数据)、创建Spring Boot项目、添加依赖(包括tk-mybatis和分页插件PageHelper),到配置数据源和MyBatis。重点讲解了实体类创建、Mapper接口定义(继承tk.mybatis.mapper.common.Mapper)以及核心API的使用,包括增删改查操作和基于

沐雨橙风ιε的博客 3560

【Spring Boot 整合 MyBatis 详细教程】

Spring Boot 与 MyBatis 的整合可以让你轻松地构建数据访问层,通过简化配置和自动配置功能,使得开发者可以更加专注于业务逻辑的实现。本文将详细介绍如何在 Spring Boot 项目中整合 MyBatis。通过以上步骤,你可以在 Spring Boot 项目中成功整合 MyBatis,实现对数据库的访问和操作。Spring Boot 的自动配置和 MyBatis 的灵活性使得开发更加高效和简单。

m0_71752625的博客 1703
上一篇: Spring boot test
下一篇: Spring boot JPA
xiaoduup
博客等级 码龄9年 23粉丝 83原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值