首页 > 其他分享 >【SpringBootWeb入门-15】Mybatis-基础操作-增改查操作

【SpringBootWeb入门-15】Mybatis-基础操作-增改查操作

时间:2023-12-19 23:12:15浏览次数:32  
标签:15 org SpringBootWeb 增改查 emp time import id Emp

1、章节回顾

上一篇文章我们讲解了Mybatis的删除操作,本篇继续学习Mybatis的新增操作:根据员工表字段,新增员工表的数据,新增的字段有:用户名、员工姓名、性别、图像、职位、入职日期、归属部门。

2、增删改查操作-新增操作

员工表emp新增数据,对应的SQL语句:

insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time)
VALUES
    ('Tom','汤姆',1,'1.jpg',1,'2005-01-01',1,now(),now());
View Code

对应的接口方法:

package com.hiker.mapper;

import com.hiker.pojo.Emp;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;

@Mapper
public interface EmpMapper {

    //根据ID来删除数据
    @Delete("delete from emp where id=#{id}")
    //public void delete(Integer id);
    public int delete(Integer id);

    //新增员工
    @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) " +
            " values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
    public void insert(Emp emp); //由于有多个参数,可以将实体类封装起来

}
View Code

对应的测试代码:

package com.hiker;

import com.hiker.mapper.EmpMapper;
import com.hiker.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;


    @Test
    public void testInsert() {
        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,1,1));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);
        //执行新增员工信息操作
        empMapper.insert(emp);
    }

}
View Code

运行单元测试的方法,看到username为Tom的记录已新增。

在这里增加一个小知识点,上述的新增操作是不涉及主键返回的,也就是说新增了一条数据,没有返回新增数据的主键是多少,例如上述新增的username为Tom的主键是20。

那我们怎么返回新增数据的主键呢:可以使用Options注解,配置keyProperty = "id",useGeneratedKeys = true。注意这里keyProperty = "id"是指主键为id字段,如果主键为其他字段,则修改即可。配置完成后会自动将生成的主键值,赋值给emp对象的id属性。

我们来修改对应的接口方法:

package com.hiker.mapper;

import com.hiker.pojo.Emp;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;

@Mapper
public interface EmpMapper {

    //新增员工
    @Options(keyProperty = "id",useGeneratedKeys = true) //会自动将生成的主键值,赋值给emp对象的id属性
    @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) " +
            " values (#{username},#{name},#{gender},#{image},#{job},#{entrydate},#{deptId},#{createTime},#{updateTime})")
    public void insert(Emp emp); //由于有多个参数,可以将实体类封装起来

}
View Code

对应的测试方法:

package com.hiker;

import com.hiker.mapper.EmpMapper;
import com.hiker.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testInsert() {
        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,1,1));
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);
        //执行新增员工信息操作
        empMapper.insert(emp);
        //输出新增数据的主键ID值
        System.out.println(emp.getId());
    }

}
View Code

运行单元测试的方法,看到username为Tom2的记录已新增,主键值为21,并且也已输出21的值在控制台中。

3、增删改查操作-修改操作

新增操作完成之后,我们来学习更新操作,根据ID来更新员工信息,此时我们是需要进行两步的操作,第一步是根据ID获取到要修改的数据,第二步是修改数据。

例如我们要修改id=20的数据记录,对应的SQL语句:

update emp set username = 'Tom1', name = '汤姆1', gender = 1 , image = '1.jpg' , job = 2, entrydate = '2012-01-01', dept_id = 2, update_time = '2022-10-01 12:12:12' where id = 20;
View Code

 对应的接口方法:

package com.hiker.mapper;

import com.hiker.pojo.Emp;
import org.apache.ibatis.annotations.*;

@Mapper
public interface EmpMapper {

    //修改员工
    @Update("update emp set username = #{username}, name = #{name}, gender = #{gender} , image = #{image} , " +
            "job = #{job}, entrydate = #{entrydate}, dept_id = #{deptId}, update_time = #{updateTime} where id = #{id}")
    public void update(Emp emp);//由于有多个参数,可以将实体类封装起来

}
View Code

对应的测试代码:

package com.hiker;

import com.hiker.mapper.EmpMapper;
import com.hiker.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    //修改员工
    @Test
    public void testUpdate() {
        Emp emp = new Emp();
        emp.setId(20);
        emp.setUsername("Tom1");
        emp.setName("1");
        emp.setImage("1.jpg");
        emp.setGender((short)1);
        emp.setJob((short)1);
        emp.setEntrydate(LocalDate.of(2000,1,1));
        emp.setUpdateTime(LocalDateTime.now());
        emp.setDeptId(1);
        //执行新增员工信息操作
        empMapper.update(emp);
    }
}
View Code

运行单元测试的方法,看到id=20的记录,其username为Tom的记录已修改为Tom1。

4、增删改查操作-查询操作

学习完最基本的增、删、改操作之后,我们来学习查询操作,我们先来学习第一个查询需求:根据ID查询。

对应的SQL语句:select * from emp where id = 20

对应的接口方法:

package com.hiker.mapper;

import com.hiker.pojo.Emp;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface EmpMapper {

    //根据ID来查询员工
    @Select("select *  from emp where id = #{id}")
    //由于根据ID查询返回的数据只有一条,所以没必要封装到集合来返回,直接封装到一个员工对象即可
    public Emp getById(Integer id);

}
View Code

对应的测试代码:

package com.hiker;

import com.hiker.mapper.EmpMapper;
import com.hiker.pojo.Emp;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper empMapper;

    //根据ID来查询员工
    @Test
    public void testgetById() {
        Emp id = empMapper.getById(20);
        System.out.println(emp);
    }
}
View Code

运行单元测试的方法,可以看到id=20的记录已经输出到控制台。

但是我们看控制台的输出中,deptId=null, createTime=null, updateTime=null 这三个字段是null值,这三个字段的值没有封装进来,但这三个字段在数据库表中是有数值的,那为什么会出现这种情况呢?这就涉及到了Mybatis的数据封装

数据封装

  • 实体类属性名 和 数据库表查询返回的字段名一致,mybatis会自动封装。
  • 如果实体类属性名 和 数据库表查询返回的字段名不一致,不能自动封装。

在这里我们可以看到,emp的实体类 deptId、createTime、updateTime与数据库表字段dept_id、create_time、update_time不一致,不能自动封装。

那怎么来解决这种问题呢?我们一般有三种处理方法。具体如下:

  • 起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。
@Select("select id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id} ")
public Emp getById(Integer id);
View Code
  • 手动结果映射:通过 @Results及@Result 进行手动结果映射。
@Select("select * from emp where id = #{id}")
@Results({
        @Result(column = "dept_id", property = "deptId"),
        @Result(column = "create_time", property = "createTime"),
        @Result(column = "update_time", property = "updateTime")})
public Emp getById(Integer id);
View Code
  • 开启驼峰命名:如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。
#开启驼峰命名自动映射,即从数据库字段名 a_column 映射到Java 属性名 aColumn。
mybatis.configuration.map-underscore-to-camel-case=true
View Code

我们常用的推荐第三种,减少代码量。

开启驼峰命名自动映射后,我们再重新运行测试代码,输出如下:

可以看到,emp的实体类 deptId、createTime、updateTime已经输出有值了。

关于Mybatis的简单增删查改操作已经学习完毕,下一篇我们继续学习Mybatis的复杂查询操作

标签:15,org,SpringBootWeb,增改查,emp,time,import,id,Emp
From: https://www.cnblogs.com/hiker0412/p/17914814.html

相关文章

  • 代码随想录算法训练营第七天|454.四数相加II,383. 赎金信,15. 三数之和,18. 四数之和
    一、454.四数相加II题目链接:LeetCode454.四数相加II学习前:思路:首先定义两个HashMap对象record12和record34,对应的key存放两个数组元素的和,value存放计算的和出现的次数接着遍历record12,若record存在与之和为0的元素,则计算两个value相乘的结果,并进行累积,作为输出的结果......
  • (原)NCP170AMX280TBG 150mA(LDO)稳压器,TPS25942ARVCR功能丰富的电源管理器件
    1、NCP170AMX280TBGLDO稳压器,150mA,超低IqNCP170系列CMOS低漏稳压器特别适用于需要超低静止电流的便携式电池供电应用。典型值为500nA的超低耗量确保了较长的电池寿命和动态瞬变升压功能,改善了无线通信应用的器件瞬变反应。该器件采用小型1×1mmxDFN4、TSOP5和SOT-......
  • IDE之VS:Visual Studio的简介(包括 VS2013、VS2015、VS2017、VS2019、VS2022)、安装、
    原文链接:https://blog.csdn.net/qq_41185868/article/details/81052119最近开始使用vs2019,应该是最新的版本。之前都是vs2015,感觉19更智能,兼容性更好,速度也更快。详细了解下这几个版本。1、简介:MicrosoftVisualStudio(简称VS)是美国微软公司的开发工具包系列产品,功能完备的I......
  • [ABC315G] Ai + Bj + Ck = X (1 <= i, j, k <= N) 题解
    原题链接:ABC315G前置知识:扩展欧几里得算法。如果还不会扩欧的话,建议先去做这道题。题意给定\(n,a,b,c,k\)。求有多少个\(x,y,z(x,y,z\len)\)满足\(ax+by+cz=k\)。思路首先看到题目给出的方程式:\(ax+by+cz=k\)。我们会发现很像扩欧板子中的:\(ax+by=k\)。只不过又多了一......
  • day15(生成器)
    1.生成器对象1.本质 还是内置有__iter__和__next__的迭代器对象2.区别 迭代器对象是解释器自动提供的 数据类型\文件对象>>>:迭代器对象 生成器对象是程序员编写出来的 代码、关键字>>>:迭代器对象(生成器)3.创建生成器的基本语法 函数体代码中填写yield关键字......
  • 15. 三数之和
    题目15.三数之和要求给你一个整数数组 nums ,判断是否存在三元组 [nums[i],nums[j],nums[k]] 满足 i!=j、i!=k 且 j!=k ,同时还满足 nums[i]+nums[j]+nums[k]==0 。请你返回所有和为 0 且不重复的三元组。注意:答案中不可以包含重复的三元组。示例......
  • springboot015粮食仓库管理系统(毕业设计,附数据库和源码)
    一.4开发的技术介绍一.4.1Springboot介绍一.4.2Java语言一.4.3MySQL数据库一.5论文的结构二需求分析二.1需求设计二.2可行性分析二.2.1技术可行性二.2.2经济可行性二.2.3操作可行性二.3功能需求分析表2-1粮食仓库管理系统功能结构图三系统设计三.1数据库概念结构......
  • 12.15
    <!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><title>房产经纪人页面</title><style>.form{width:600px;margin:0auto;/*bor......
  • 10.15
    虽然SQL是一门ANSI(AmericanNationalStandardsInstitute美国国家标准化组织)标准的计算机语言,但是仍然存在着多种不同版本的SQL语言。然而,为了与ANSI标准相兼容,它们必须以相似的方式共同地来支持一些主要的命令(比如SELECT、UPDATE、DELETE、INSERT、WHERE等等)。要创......
  • (15-418)Lecture 3 Parallel Programming Abstractions
    抽象VS实现实例:ISPC程序ISPC是一种SPMD(singleprogrammultipledata)编译器。利用ISPC编写的计算sin(x)的程序如下图:ISPC提供了一种抽象,当调用ISPC函数时(即程序中调用sinx的语句),会产生一个gang,这个gang含有多个ISPC实例,每个实例会执行自己的代码,当每个实例都执行完后,恢复原先......