【mybatis-plus问题集锦系列】使用mybatis实现数据的基础增删改查

news2025/5/15 0:25:33

使用mybatis实现数据的基础增删改查,简单的增删改查操作方法步骤

代码实现

  • pom.xml
<dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.4</version>
        </dependency>

        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter-test</artifactId>
            <version>3.0.4</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
  • EmpMapper.interface
/**
 * @author gaofeng
 * @date 2025-01-04 - 18:02
 */
@Mapper
public interface EmpMapper {

    @Select("select * from tb_emp")
    public List<Emp> getAllEmpList();

    @Delete("delete from tb_emp where id = #{id}")
    public int deleteEmp(Integer id);
}
  • pojo.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * @author gaofeng
 * @date 2025-01-04 - 17:58
 */

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Emp {
    private Integer id;
    private String username;
    private String password;
    private String name;
    private Short gender;
    private String image;
    private Short job;
    private LocalDate entrydate;
    private Integer geptId;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}
  • application.properties文件
server.port=9090
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/javaweb
spring.datasource.username=root
spring.datasource.password=123456

# 控制台输出mybatis的日志信息
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  • 测试效果

    • 查询所有数据
    @Test
     public void getAllEmpList(){
         List<Emp> allEmpList = empMapper.getAllEmpList();
         allEmpList.stream().forEach(emp -> {
             System.out.println(emp);
         });
     }
    

    在这里插入图片描述

    • 根据id删除记录
    @Test
    public void deleteEmpById(){
        int count = empMapper.deleteEmp(17);
        System.out.println(count);
    }
    

    在这里插入图片描述

    • 增加

      @Test
      public void insertEmp(){
          Emp emp = new Emp();
          emp.setUsername("Tom");
          emp.setName("汤姆");
          emp.setImage("1.jpg");
          emp.setGender((short)1);
          emp.setJob((short)1);
          emp.setEntrydate(LocalDate.of(2000,01,01));
          emp.setCreateTime(LocalDateTime.now());
          emp.setUpdateTime(LocalDateTime.now());
          emp.setDeptId(1);
          empMapper.insert(emp);
      }
      

      在这里插入图片描述

    • 新增返回主键

      	@Options(keyProperty = "id",useGeneratedKeys = true)  // 加上这个注解
          @Insert("insert into tb_emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) VALUES\n" +
                  "            (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
          public void insert(Emp emp);
      
      @Test
      public void insertEmp(){
          Emp emp = new Emp();
          emp.setUsername("Tom2");
          emp.setName("汤姆2");
          emp.setImage("1.jpg");
          emp.setGender((short)1);
          emp.setJob((short)1);
          emp.setEntrydate(LocalDate.of(2000,01,01));
          emp.setCreateTime(LocalDateTime.now());
          emp.setUpdateTime(LocalDateTime.now());
          emp.setDeptId(1);
          empMapper.insert(emp);
      
          System.out.println(emp.getId());
      }
      

      在这里插入图片描述 这样在数据库中就对应上了

      在这里插入图片描述

    • 更新

          @Update("update tb_emp set username = #{username},name = #{name},gender = #{gender},\n" +
                  "                  image=#{image},job=#{job},entrydate=#{entrydate},dept_id=#{deptId},\n" +
                  "                  update_time=#{updateTime} where id = #{id}")
          public void update(Emp emp);
      
       @Test
        public void updateEmp(){
            Emp emp = new Emp();
            emp.setId(18);
            emp.setUsername("Tom3");
            emp.setName("汤姆3");
            emp.setImage("1.jpg");
            emp.setGender((short)1);
            emp.setJob((short)1);
            emp.setEntrydate(LocalDate.of(2000,01,01));
            emp.setUpdateTime(LocalDateTime.now());
            emp.setDeptId(1);
            empMapper.update(emp);
      //        System.out.println(emp.getId());
        }
      

      在这里插入图片描述
      在这里插入图片描述

    • 根据id查询

      @Select("select * from tb_emp where id = #{id}")
      public Emp getById(Integer id);
    
    // 根据id
      @Test
      public  void getById(){
          Emp emp = empMapper.getById(19);
          System.out.println(emp);
      }
    

在这里插入图片描述

解决方法一:就是起别名,需要列出所有的字段,不能用*代替了
解决方法二:使用Results注解

 	@Results({
           @Result(column = "dept_id",property = "deptId"),
           @Result(column = "create_time",property = "createTime"),
           @Result(column = "update_time",property = "updateTime")
   })
   @Select("select * from tb_emp where id = #{id}")
   public Emp getById(Integer id);	

在这里插入图片描述
解决方法三:使用mybatis的配置,开启识别驼峰命名

mybatis.configuration.map-underscore-to-camel-case = true
  • 条件查询
    • 方式1
 @Select("select * from tb_emp where name like '%${name}%' and gender = #{gender}\n" +
           "and entrydate between #{begin} and #{end} order by update_time desc;\n")
 public List<Emp> listEmp(String name,Short gender, LocalDate begin,LocalDate end);

  • 方式2
 @Select("select * from tb_emp where name like concat('%',#{name},'%') and gender = #{gender}\n" +
           "and entrydate between #{begin} and #{end} order by update_time desc;\n")
   public List<Emp> listEmp(String name,Short gender, LocalDate begin,LocalDate end);
@Test
 public void testList(){
     List<Emp> empList = empMapper.listEmp("张",(short)1, LocalDate.of(2010, 1, 1), LocalDate.of(2020, 1, 1));
     System.out.println(empList);
 }

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2271815.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

tlias项目实战笔记

一个小项目写了一个多月&#xff0c;在考试周穿插&#xff0c;终于能有时间来写个小总结了&#xff0c;废话少说&#xff0c;我们直接来步入正题。 一、项目开发规范 1.开发风格Restful 案例是基于当前最为主流的前后端分离模式进行开发。 在前后端分离的开发模式中&#xff…

Arduino Uno简介与使用方法

目录 一、Arduino Uno概述 1. 硬件特性 2. 开发环境 二、Arduino Uno的基本使用方法 1. 硬件连接 2. 软件编程 三、Arduino Uno编程基础 1. 基本语法 2. 常用函数 四、Arduino Uno应用举例 1. LED闪烁 2. 温度检测 3. 超声波测距 五、Arduino Uno的扩展与应用 1…

go 模拟TCP粘包和拆包,及解决方法

1. 什么是 TCP 粘包与拆包&#xff1f; 粘包&#xff08;Sticky Packet&#xff09; 粘包是指在发送多个小的数据包时&#xff0c;接收端会将这些数据包合并成一个数据包接收。由于 TCP 是面向流的协议&#xff0c;它并不会在每次数据发送时附加边界信息。所以当多个数据包按顺…

新能源电动汽车动力电池技术

新能源电动汽车动力电池技术是新能源汽车发展的核心之一&#xff0c;以下是动力电池技术的一些关键方面&#xff1a; 技术进展 能量密度提升&#xff1a;近年来&#xff0c;动力电池的能量密度有了显著提升&#xff0c;从2010年的100Wh/kg提高到2024年的300Wh/kg。能量密度的…

仓颉笔记——windows11安装启用cangjie语言,并使用vscode编写“你好,世界”

2025年1月1日第一篇日记&#xff0c;大家新年好。 去年就大致看了一下&#xff0c;感觉还不错&#xff0c;但一直没上手&#xff0c;这次借着元旦的晚上安装了一下&#xff0c;今年正式开动&#xff0c;公司众多的应用国产化正等着~~ 第一步&#xff1a;准备 官网&#xff1a;…

JVM对象内存结构

1对象内存结构说明 注意&#xff1a; 如果对象为数组对象&#xff0c;在对象头后面有4字节存储数组长度&#xff1b; 1.1对象头 对象头分为Mark Word和Class Pointer两部分&#xff1b; Mark Word&#xff1a;对象基础信息 32位操作系统中占4字节&#xff0c;64位操作系统中占8…

doris:基于 Arrow Flight SQL 的高速数据传输链路

Doris 基于 Arrow Flight SQL 协议实现了高速数据链路&#xff0c;支持多种语言使用 SQL 从 Doris 高速读取大批量数据。 用途​ 从 Doris 加载大批量数据到其他组件&#xff0c;如 Python/Java/Spark/Flink&#xff0c;可以使用基于 Arrow Flight SQL 的 ADBC/JDBC 替代过去…

算法题(25):只出现一次的数字(三)

审题&#xff1a; 该题中有两个元素只出现一次并且其他元素都出现两次&#xff0c;需要返回这两个只出现一次的数&#xff0c;并且不要求返回顺序 思路: 由于对空间复杂度有要求&#xff0c;我们这里不考虑哈希表。我们采用位运算的方法解题 方法&#xff1a;位运算 首先&#…

HTML——75. 内联框架

<!DOCTYPE html> <html><head><meta charset"UTF-8"><title>内联框架</title><style type"text/css">iframe{width: 100%;height: 500px;}</style></head><body><!--iframe元素会创建包含…

MotionCtrl: A Unified and Flexible Motion Controller for Video Generation 论文解读

目录 一、概述 二、相关工作 三、前置知识 1、LVDM Introduction 2、LVDM Method 3、LVDM for Short Video Generation 4、Hierarchical LVDM for Long Video Generation 5、训练细节 6、推理过程 四、MotionCtrl 1、CMCM 2、OMCM 3、训练策略 五、实验 一、概述…

vue2实现excel文件预览

一、插件 通过xlsx插件解析excel数据&#xff0c;对解析后的html组件进行渲染展示。 npm install xlsx 二、完整代码 <template><!-- excel文件预览 --><divelement-loading-text"拼命加载中"element-loading-spinner"el-icon-loading"…

uniapp:跳转第三方地图

1.跳转第三方高德地图 //跳转地图 toMap(item){uni.navigateTo({url: (window.location.href https://uri.amap.com/navigation?to${item.lng},${item.lat},${item.shopName}&modecar&policy1&srchttps://gawl.gazhcs.com/wap/index.html&callnative0)}) },…

纯前端实现将pdf转为图片(插件pdfjs)

需求来源 预览简历功能在移动端&#xff0c;由于用了一层iframe把这个功能嵌套在了app端&#xff0c;再用一个iframe来预览&#xff0c;只有ios能看到&#xff0c;安卓就不支持&#xff0c;查了很多资料和插件&#xff0c;原理基本上都是用iframe实现的。最终转换思路&#xf…

【亚马逊云科技】基于Amazon EKS部署高可用的OceanBase的最佳实践

一、前言 随着企业业务的快速发展和数据量的不断增长&#xff0c;高性能、高可用的数据库解决方案成为了关键需求。OceanBase作为一款分布式关系型数据库&#xff0c;以其高扩展性、高可用性和高性能的特点&#xff0c;逐渐受到企业的广泛关注。然而&#xff0c;在复杂的分布式…

Linux postgresql-15部署文档

一、PostgreSQL的安装 1、下载地址 postgresql安装包下载地址&#xff1a;https://www.postgresql.org/download/linux/redhat/ 2、安装脚本 复制下面的安装脚本即可&#xff1a; sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64…

用python编写一个放烟花的小程序

import pygame import random # 代码解释及使用说明&#xff1a; # 首先&#xff0c;导入 pygame 和 random 库。pygame 用于创建游戏窗口和图形绘制&#xff0c;random 用于生成随机数。 # 初始化 pygame&#xff0c;并设置屏幕尺寸为 800x600 像素&#xff0c;设置窗口标题为…

旧服务改造及微服务架构演进

旧服务改造及微服务架构演进 微服务架构演进1.微服务架构2.微服务架构的特点3.单体架构与微服务架构之间的对比4.微服务架构演进历程 旧服务改造1. 微服务拆分的一些通用原则2.微服务拆分策略&#xff08;1&#xff09;功能维度拆分策略&#xff08;2&#xff09;非功能维度拆分…

Science Robotics让软机器人“活”得更久的3D打印!

软机器人硬件在医疗、探索无结构环境等领域有广泛应用&#xff0c;但其生命周期有限&#xff0c;导致资源浪费和可持续性差。软机器人结合软硬组件&#xff0c;复杂组装和拆卸流程使其难以维修和升级。因此&#xff0c;如何延长软机器人的生命周期并提高其可持续性成为亟待解决…

MyBatis执行一条sql语句的流程(源码解析)

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 MyBatis执行一条sql语句的流程&#xff08;源码解析&#xff09; MyBatis执行sql语句的流程加载配置文件加载配置文件的流程 创建sqlsessionFactory对象解析Mapper创建sqlses…

Git命令行的使用

目录 一、什么是Git 1、本地仓库 vs 远端仓库 本地仓库 远端仓库 2、.git vs .gitignore .git .gitignore 二、使用Git命令 1、安装git 2、git首次使用需要配置用户邮箱和用户名 3、上传目录/文件到远端仓库步骤 1&#xff09;创建放置文件的目录 2&#xff09;cd…