初学MyBatis小结

0 简介

MyBatis官网介绍

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

1 准备

1.1 创建一个空的SpringBoot项目

创建一个SpringBoot的项目,配置好相关依赖。

1.2 配置SpringBoot项目相关信息 

空项目床架完成后,配置properties配置文件,连接mysql数据库。

创建pojo,mapper包,在两个包下分别创建Emp.java,EmpMapper.java接口。

Emp.java


@Data
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    private Integer id;//ID
    private String username;//用户名
    private String password;//密码
    private String name;//姓名
    private Short gender;//性别,1:男,2:女
    private String image;//图像
    private Short job;//职位,说明,1:班主任,2:讲师,3:学工主管4 教研主管, 5 咨询师
    private LocalDate entryDate;//入职时间
    private Integer deptId;//部门ID
    private LocalDateTime createTime;//创建时间
    private LocalDateTime updateTime;//修改时间
}

EmpMapper.java 

@Mapper
public interface EmpMapper {
   
}

SpringBoot项目结构

 

 1.3 创建数据库

-- 部门管理
create table dept(
    id int unsigned primary key auto_increment comment '主键ID',
    name varchar(10) not null unique comment '部门名称',
    create_time datetime not null comment '创建时间',
    update_time datetime not null comment '修改时间'
) comment '部门表';

insert into dept (id, name, create_time, update_time) values(1,'学工部',now(),now()),(2,'教研部',now(),now()),(3,'咨询部',now(),now()), (4,'就业部',now(),now()),(5,'人事部',now(),now());



-- 员工管理
create table emp (
  id int unsigned primary key auto_increment comment 'ID',
  username varchar(20) not null unique comment '用户名',
  password varchar(32) default '123456' comment '密码',
  name varchar(10) not null comment '姓名',
  gender tinyint unsigned not null comment '性别, 说明: 1 男, 2 女',
  image varchar(300) comment '图像',
  job tinyint unsigned comment '职位, 说明: 1 班主任,2 讲师, 3 学工主管, 4 教研主管, 5 咨询师',
  entrydate date comment '入职时间',
  dept_id int unsigned comment '部门ID',
  create_time datetime not null comment '创建时间',
  update_time datetime not null comment '修改时间'
) comment '员工表';

INSERT INTO emp
	(id, username, password, name, gender, image, job, entrydate,dept_id, create_time, update_time) VALUES
	(1,'jinyong','123456','金庸',1,'1.jpg',4,'2000-01-01',2,now(),now()),
	(2,'zhangwuji','123456','张无忌',1,'2.jpg',2,'2015-01-01',2,now(),now()),
	(3,'yangxiao','123456','杨逍',1,'3.jpg',2,'2008-05-01',2,now(),now()),
	(4,'weiyixiao','123456','韦一笑',1,'4.jpg',2,'2007-01-01',2,now(),now()),
	(5,'changyuchun','123456','常遇春',1,'5.jpg',2,'2012-12-05',2,now(),now()),
	(6,'xiaozhao','123456','小昭',2,'6.jpg',3,'2013-09-05',1,now(),now()),
	(7,'jixiaofu','123456','纪晓芙',2,'7.jpg',1,'2005-08-01',1,now(),now()),
	(8,'zhouzhiruo','123456','周芷若',2,'8.jpg',1,'2014-11-09',1,now(),now()),
	(9,'dingminjun','123456','丁敏君',2,'9.jpg',1,'2011-03-11',1,now(),now()),
	(10,'zhaomin','123456','赵敏',2,'10.jpg',1,'2013-09-05',1,now(),now()),
	(11,'luzhangke','123456','鹿杖客',1,'11.jpg',5,'2007-02-01',3,now(),now()),
	(12,'hebiweng','123456','鹤笔翁',1,'12.jpg',5,'2008-08-18',3,now(),now()),
	(13,'fangdongbai','123456','方东白',1,'13.jpg',5,'2012-11-01',3,now(),now()),
	(14,'zhangsanfeng','123456','张三丰',1,'14.jpg',2,'2002-08-01',2,now(),now()),
	(15,'yulianzhou','123456','俞莲舟',1,'15.jpg',2,'2011-05-01',2,now(),now()),
	(16,'songyuanqiao','123456','宋远桥',1,'16.jpg',2,'2010-01-01',2,now(),now()),
	(17,'chenyouliang','123456','陈友谅',1,'17.jpg',NULL,'2015-03-21',NULL,now(),now());

 idea连接mysql数据库

2 MyBatis基于注解开发

2.1 select语句

在EmpMapper.java接口中写入:

@Mapper
public interface EmpMapper {
    @Select("select `id`, `username`, `password`, `name`, `gender`, `image`, `job`, `entrydate` as `entryDate`, `dept_id` as `deptId`, `create_time` as `createTime`, `update_time` as `updateTime` from emp")
    public List<Emp> list();
}

直接在方法上添加@Select()注解即可,括号内填写查询语句,由于数据库中的字段名与我们的Emp.java类中的属性名不一致,所以,我们需要设置别名,以便MyBatis能顺利将查询出的数据封装到Emp.对象中。

测试:

@SpringBootTest
class SprintbootMybatis02ApplicationTests {
    //Spring的依赖注入机制
    //过去我们创建对象为 private EmpMapper empMapper = new EmpMapperImpl();
    //需要有个实现EmpMapper接口的实现类,而引入Spring后,则不需要自己手动创建对象,直接添加
    //@Autowired注解,Spring会将实现EmpMapper接口的类的对象直接创建好,然后赋值给empMapper成员。
    //当然要实现此功能,需要在EmpMapper.java接口上添加@Mapper注解,Spring才会控制反转,将该类的对象创建过程由Spring来控制
    @Autowired
    private EmpMapper empMapper;

    @Test
    public void testListEmp(){
        for (Emp emp : empMapper.list()) {
            System.out.println(emp);
        }
    }
}

 结果:

2.2  delete语句

@Mapper
public interface EmpMapper {
    @Select("select `id`, `username`, `password`, `name`, `gender`, `image`, `job`, `entrydate` as `entryDate`, `dept_id` as `deptId`, `create_time` as `createTime`, `update_time` as `updateTime` from emp")
    public List<Emp> list();

    //由于删除的记录不是固定的,我们不能给写死,需要传递一个参数,来实现删除指定id记录。
    //这里有两种方式:
    //方式一:@Delete("delete from emp where id = ${id}")
    //这种是拼接字符串,会有sql注入风险,一般不用
    //方式二:@Delete("delete from emp where id = #{id}")
    //预编译sql,推荐使用
    //#{...}中的变量一般与对应方法中参数变量名字相一致

    @Delete("delete from emp where id = #{id}")
    public int delete(Integer id);
}

2.3 insert语句和update语句

@Mapper
public interface EmpMapper {
    @Select("select `id`, `username`, `password`, `name`, `gender`, `image`, `job`, `entrydate` as `entryDate`, `dept_id` as `deptId`, `create_time` as `createTime`, `update_time` as `updateTime` from emp")
    public List<Emp> list();

    @Delete("delete from emp where id = #{id}")
    public int delete(Integer id);

//    @Results({
//            @Result(column = "dept_id",property = "deptId"),
//            @Result(column = "create_time",property = "createTime"),
//            @Result(column = "update_time",property = "updateTime"),
//            @Result(column = "entrydate",property = "entryDate")
//    })//数据库中表的字段与类中的属性名不一致,可以采用映射的方式
    @Select("select * from emp where id = #{id}")
    public Emp queryEmpById(Integer id);

    @Options(keyProperty = "id",useGeneratedKeys = true)//返回自动生成的主键,并放入emp对象中
    @Insert("insert into emp(id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time)\n" +
            "values (#{id},#{username},#{password},#{name},#{gender},#{image},#{job},#{entryDate},#{deptId},#{createTime},#{updateTime})")
    public int insertEmp(Emp emp);

    //当参数变量过多时,我们可以采用封装的思想,将参数封装到类中
    @Update("update emp set username = #{username},password=#{password},name = #{name},gender=#{gender},image=#{image}, job=#{job},entrydate=#{entryDate},dept_id=#{deptId},create_time=#{createTime},update_time=#{updateTime} where id=#{id}")
    public int update(Emp emp);
}

3 MyBatis基于XML开发

3.1 配置

在resources下创建com/xiaoyan/mapper结构的文件,这里要与src下的EmpMapper所在的包结构对应命名。

然后在目录下床架一个EmpMapper.xml映射文件。

3.2 properties配置文件

添加最后两行,可以在控制台输出执行的sql语句

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.username=root
spring.datasource.password=123456
# 在application.properties中添加:开启mybatis驼峰命名方式映射
#该方式有个严格的前提,数据库中的命名方式为x_yz,java类中的属性命名xYzmn
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

3.3 mybaitsx插件

可以使用该插件实现mapper中方法的快速定位。在file->setting->plugins中直接搜索即可。

 3.3 编写EmpMapper.xml映射文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace命名空间需要与对应方法所在包结构一致-->
<mapper namespace="com.xiaoyan.mapper.EmpMapper">
 
</mapper>

3.4 编写动态SQL

原有的select条件查询语句

<select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        where name like concat('%',#{name},'%')
              and gender = #{gender}
              and entrydate between #{begin} and #{end}
        order by update_time desc
</select>

 动态sql语句

<select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        where
    
             <if test="name != null">
                 name like concat('%',#{name},'%')
             </if>
             <if test="gender != null">
                 and gender = #{gender}
             </if>
             <if test="begin != null and end != null">
                 and entrydate between #{begin} and #{end}
             </if>
    
        order by update_time desc
</select>

 优化:

<where>只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR

<select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        <where>
             <!-- if做为where标签的子元素 -->
             <if test="name != null">
                 and name like concat('%',#{name},'%')
             </if>
             <if test="gender != null">
                 and gender = #{gender}
             </if>
             <if test="begin != null and end != null">
                 and entrydate between #{begin} and #{end}
             </if>
        </where>
        order by update_time desc
</select>

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

C语言分析基础排序算法——归并排序

目录 归并排序 递归版本 非递归版本 非递归版本的问题 归并排序小优化 归并排序 归并排序&#xff0c;分为分治以及合并&#xff0c;分治部分可以使用递归或者非递归完成&#xff0c;归并排序的基本思路是&#xff1a;将已有序的子序列合并&#xff0c;得到完全有序的序列…

qiankun:vite/webpack项目配置

相关博文&#xff1a; https://juejin.cn/post/7216536069285429285?searchId202403091501088BACFF113F980BA3B5F3 https://www.bilibili.com/video/BV12T411q7dq/?spm_id_from333.337.search-card.all.click qiankun结构&#xff1a; 主应用base&#xff1a;vue3historyv…

基于SpringCache实现数据缓存

SpringCache SpringCache是一个框架实现了基本注解的缓存功能,只需要简单的添加一个EnableCaching 注解就能实现缓存功能 SpringCache框架只是提供了一层抽象,底层可以切换CacheManager接口的不同实现类即使用不同的缓存技术,默认的实现是ConcurrentMapCacheManagerConcurren…

中间件 | Kafka - [常见问题]

INDEX 1 为什么快2 消息丢失2.1 消息丢失位置2.2 如何避免消息丢失 3 顺序消费 1 为什么快 kafka使用的是基于文件的顺序存储 代价是只能通过offset标记消费情况并总 partition 数越高&#xff0c;性能越下降&#xff0c;可降低一个数量级 每个 partition 的消息会保存在一个独…

C++day3——类中的成员函数

思维导图&#xff1a; 2、设计一个Per类&#xff0c;类中包含私有成员&#xff1a;姓名、年龄、指针成员身高、体重&#xff0c;再设计一个Stu类&#xff0c;类中包含私有成员&#xff1a;成绩、Per类对象p1&#xff0c;设计这两个类的构造函数、析构函数和拷贝构造函数。 #in…

力扣串题:验证回文串2

bool judge(char *s,int m,int n){while(m<n){if(s[m]!s[n]){return false;}m,n--;}return true; } bool validPalindrome(char * s){for(int i0,jstrlen(s)-1;i<j;i,j--){if(s[i]!s[j]){return (judge(s,i1,j)||judge(s,i,j-1));}}return true; }这个题直接背大佬代码吧…

彩虹外链网盘界面UI美化版超级简洁好看

彩虹外链网盘界面UI美化版 彩虹外链网盘&#xff0c;是一款PHP网盘与外链分享程序&#xff0c;支持所有格式文件的上传&#xff0c;可以生成文件外链、图片外链、音乐视频外链&#xff0c;生成外链同时自动生成相应的UBB代码和HTML代码&#xff0c;还可支持文本、图片、音乐、…

Albumentations——广泛应用于工业界、学术界、AI竞赛和开源项目中的CV数据增强工具

Albumentations: fast and flexible image augmentationsDiscover Albumentations: an open-source library offering efficient and customizable image augmentations to boost machine learning and computer vision model performance.https://albumentations.ai/

HM v.16.22 顺序读源码day1---encmain.cpp

文章目录 encmain.cpp引入的库执行主体1. 读取输入的配置文件2. 编码启动和过程计时 实现细节1. cTAppEncTop.parseCfg( argc, argv )&#xff1b;2. df::program_options_lite::ParseFailure;3. EnvVar::printEnvVar();4. EnvVar::printEnvVarInUse();5. printMacroSettings()…

plt保存PDF矢量文件中嵌入可编辑字体(可illustrator编辑)

背景&#xff1a; 用默认 plt.savefig() 保存图片&#xff0c;图中文字是以瞄点保存&#xff0c;而不是以文字格式。在编辑矢量图中&#xff0c;无法调整文字大小和字体。 方法&#xff1a; import matplotlib.pyplot as plt import numpy as np# ------输出的图片为illustr…

RabbitMQ备份交换机与优先级队列

1. 备份交换机 备份交换机可以理解为 RabbitMQ 中交换机的“备胎”&#xff0c;当我们为某一个交换机声明一个对应的备份交换机时&#xff0c;就是为它创建一个备胎&#xff0c;当交换机接收到一条不可路由消息时&#xff0c;将会把这条消息转发到备份交换机中&#xff0c;由备…

数据仓库的基本概念、基本特征、体系结构

个人看书学习心得及日常复习思考记录&#xff0c;个人随笔。 数据仓库的基本概念、基本特征 数据仓库的定义&#xff1a;数据仓库是一个面向主题的、集成的、不可更新的、随时间不断变化的数据集合&#xff0c;用以更好地支持企业或组织的决策分析处理。 数据仓库中数据的4个…

26-Java访问者模式 ( Visitor Pattern )

Java访问者模式 摘要实现范例 访问者模式&#xff08;Visitor Pattern&#xff09;使用了一个访问者类&#xff0c;它改变了元素类的执行算法&#xff0c;通过这种方式&#xff0c;元素的执行算法可以随着访问者改变而改变访问者模式中&#xff0c;元素对象已接受访问者对象&a…

Unity2019.2.x 导出apk 安装到安卓Android12+及以上的系统版本 安装出现-108 安装包似乎无效的解决办法

Unity2019.2.x 导出apk 安装到安卓Android12及以上的系统版本 安装出现-108 安装包似乎无效的解决办法 导出AndroidStudio工程后 需要设置 build.gradle文件 // GENERATED BY UNITY. REMOVE THIS COMMENT TO PREVENT OVERWRITING WHEN EXPORTING AGAINbuildscript {repositor…

python-0007-django模版

介绍 模版是对js&#xff0c;html等资源的封装 新建 在项目路径下新建模版文件夹templates&#xff08;可以为其他名称&#xff09;&#xff0c;要是想细分业务的话&#xff0c;还可以在templates路径下继续建文件夹。如下图&#xff1a; 注册模版 在项目的settings找到T…

超越营销:交易性邮件如何塑造现代沟通

在我们的电子邮件自动化系列文章中&#xff0c;我们继续探讨交易性邮件的重要性。这些邮件对于向收件人传递实时更新和可操作信息至关重要&#xff0c;是企业运营不可或缺的一部分。 运营触点 在现代沟通中&#xff0c;交易性邮件扮演着不可或缺的角色&#xff0c;尤其是在企…

String类及其常用方法

文章目录 1.String类的特性与使用1.1 String类的特性1.2 String对象的创建方式1.3 String 的使用&#xff08;不同的拼接操作&#xff09; 2.String常用方法2.1 String的常用方法一2.2 String常用方法二2.3 String常用方法三 1.String类的特性与使用 1.1 String类的特性 Stri…

使用Barrier共享鼠标键盘,通过macos控制ubuntu系统

之前文章写过如何使用barrrier通过windows系统控制ubuntu系统&#xff0c;该文章将详细介绍如何使用barrier通过macos系统控制ubuntu系统 一、macOS安装barrier macOS版本barrier链接 1、双击点开安装包 2、将安装包里的barrier拷贝到macOS的达达->应用程序中 3、在达达…

Spring启动“--”设置参数没生效

现象 在idea中启动SpringBoot项目时&#xff0c;使用“--”设置的启动参数没有生效&#xff0c;如修改端口号“--server.port8082” 原因 排查发现是因为在使用SpringApplication.run启动项目时&#xff0c;没有将args参数传入run方法。 修复方案 SpringApplication.run参数中…

当matplotlib遇见“赛博朋克”

本次分享一个Python可视化工具cyberpunk,轻松让图表变得“赛博朋克”。 案例1 import matplotlib.pyplot as plt import mplcyberpunkplt.style.use("cyberpunk") #调用cyberpunk styleplt.plot([1, 3, 9, 5, 2, 1, 1], marker=o) plt.plot([4, 5, 5, 7, 9, 8, 6…