MyBatis 基础操作

devtools/2024/10/18 15:52:23/

新建springboot项目,添加LombokMybatisMySQL的依赖项。

在这里插入图片描述

application.properties中引入数据库连接信息。

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/test
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=mysql

创建对应的实体类(实体类属性采用驼峰命名)

package com.mybatis_demo2.pojo;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.time.LocalDate;
import java.time.LocalDateTime;@Data
@NoArgsConstructor
@AllArgsConstructor
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;     //LocalDate类型对应数据表中的date类型private Integer deptId;private LocalDateTime createTime;//LocalDateTime类型对应数据表中的datetime类型private LocalDateTime updateTime;
}

准备mapper接口

package com.mybatis_demo2.mapper;import org.apache.ibatis.annotations.Mapper;/*@Mapper注解:表示当前接口为mybatis中的Mapper接口程序运行时会自动创建接口的实现类对象(代理对象),并交给Spring的IOC容器管理
*/
@Mapper
public interface EmpMapper {}

完成之后的项目目录为:

在这里插入图片描述

删除

接口方法:

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

#{id}表示要删除变量名的值。

如果mapper接口方法形参只有一个普通类型的参数,#{...}里面的属性名可以随便写。

void表示没有返回值,int表示一次操作删除了多少个记录。

在这里插入图片描述

日志输入

在Mybatis当中我们可以借助日志,查看到sql语句的执行、执行传递的参数以及执行结果。具体操作如下:

  1. 打开application.properties文件

  2. 开启mybatis的日志,并指定输出到控制台

#指定mybatis输出日志的位置, 输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

开启日志之后,我们再次运行单元测试,可以看到在控制台中,输出了以下的SQL语句信息:

在这里插入图片描述

?是预编译SQL的参数占位符。采用预编译SQL的两个优势:

  • 性能更高:预编译SQL,编译一次之后会将编译后的SQL语句缓存起来,后面再次执行这条语句时,不会再次编译。(只是输入的参数不同)
  • 更安全(防止SQL注入):将敏感字进行转义,保障SQL的安全性。

参数占位符

在Mybatis中提供的参数占位符有两种:${…} 、#{…}

  • #{…}

    • 执行SQL时,会将#{…}替换为?,生成预编译SQL,会自动设置参数值
    • 使用时机:参数传递,都使用#{…}
  • ${…}

    • 拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入问题
    • 使用时机:如果对表名、列表进行动态设置时使用

注意事项:在项目开发中,建议使用#{…},生成预编译SQL,防止SQL注入安全。

新增

接口方法:

@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);

在这里插入图片描述

说明:#{…} 里面写的名称是对象的属性名

主键返回

在数据添加成功后,需要获取插入数据库数据的主键。

默认情况下,执行插入操作时,是不会主键值返回的。如果我们想要拿到主键值,需要在Mapper接口中的方法上添加一个Options注解,并在注解中指定属性useGeneratedKeys=true和keyProperty=“实体类属性名”。

@Mapper
public interface EmpMapper {//会自动将生成的主键值,赋值给emp对象的id属性@Options(useGeneratedKeys = true,keyProperty = "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);}

更新

接口方法:

    @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 int updateEmp(Emp emp);

查询

接口方法:

    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from tb_emp where id=#{id}")public Emp getById(Integer id);

数据封装

我们看到查询返回的结果中大部分字段是有值的,但是deptId,createTime,updateTime这几个字段是没有值的,而数据库中是有对应的字段值的,这是为什么呢?

原因如下:

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

解决方法;

  1. 给字段起别名,让别名与实体类属性一致

    @Select("select id, username, password, name, gender, image, job, entrydate, " +"dept_id AS deptId, create_time AS createTime, update_time AS updateTime " +"from emp " +"where id=#{id}")
    public Emp getById(Integer id);
    
  2. 通过@Results@Result注解手动映射封装

    @Results({@Result(column = "dept_id", property = "deptId"),@Result(column = "create_time", property = "createTime"),@Result(column = "update_time", property = "updateTime")})
    @Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")
    public Emp getById(Integer id);
    
  3. 开启mybatis的驼峰命名自动映射开关

    application.properties

    # 驼峰命名自动映射开关 a_column => aColumn
    mybatis.configuration.map-underscore-to-camel-case=true
    

查询(条件查询)

  • 方法1

    @Mapper
    public interface EmpMapper {@Select("select * from emp " +"where name like '%${name}%' " +"and gender = #{gender} " +"and entrydate between #{begin} and #{end} " +"order by update_time desc")public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
    }
    

    上述方式注意事项:

    1. 方法中的形参名和SQL语句中的参数占位符名保持一致
    2. 模糊查询使用${…}进行字符串拼接,这种方式呢,由于是字符串拼接,并不是预编译的形式,所以效率不高、且存在sql注入风险。
  • 方法2(推荐,解决SQL注入问题

    使用MySQL提供的字符串拼接函数:concat(‘%’ , ‘关键字’ , ‘%’)。

    @Mapper
    public interface EmpMapper {@Select("select * from emp " +"where name like concat('%',#{name},'%') " +"and gender = #{gender} " +"and entrydate between #{begin} and #{end} " +"order by update_time desc")public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);}
    

    参数名说明

    在springboot2.x版本中

    在这里插入图片描述

在springboot的1.x版本/单独使用mybatis

在这里插入图片描述


http://www.ppmy.cn/devtools/125125.html

相关文章

4.stm32 GPIO输入

按键简介 按键&#xff1a;常见的输入设备&#xff0c;按下导通&#xff0c;松手断开 按键抖动&#xff1a;由于按键内部使用的是机械式弹簧片来进行通断的&#xff0c;所以在按下和松手的瞬间会伴随有一连串的抖动 传感器模块简介 传感器模块&#xff1a;传感器元件&#…

您是否也在寻找免费的 PDF 编辑器工具?10个备选PDF 编辑器工具

您是否也在寻找免费的 PDF 编辑器工具&#xff1f; 如果是&#xff0c;那么您在互联网上处于最佳位置&#xff01; 本指南中提到的所有 10 大免费 PDF 编辑器工具都易于使用&#xff0c;可以允许您添加文本、更改图像、添加图形、填写表格、添加签名等等。 因此&#xff0c;…

Maven 入门详解

在 Java 世界中&#xff0c;项目依赖管理就像是一张错综复杂的网&#xff0c;稍有不慎就会陷入 “依赖地狱”。而 Maven&#xff0c;就像一位经验丰富的"项目经理"&#xff0c;为我们提供了一套标准化的项目管理方案&#xff0c;将混乱的依赖关系梳理得井井有条。 1.…

Journey Training:o1的一次复现尝试,极长思维链的合成

知乎&#xff1a;啦啦啦啦&#xff08;已授权&#xff09;链接&#xff1a;https://zhuanlan.zhihu.com/p/902522340 论文&#xff1a;O1 Replication Journey: A Strategic Progress Report链接&#xff1a;https://github.com/GAIR-NLP/O1-Journey 这篇论文记录了一次o1复现尝…

Halcon模板匹配

create_shape_model_xld&#xff08;Contours : : NumLevels, AngleStart, AngleExtent, AngleStep, Optimization, Metric, MinContrast : ModelID) NumLevels&#xff1a;金字塔的层数&#xff0c;可以设置为"auto"或0-10的整数。层数越大&#xff0c;匹配所需时间…

企业水、电、气、热等能耗数据采集系统

介绍 通过物联网技术&#xff0c;采集企业水、电、气、热等能耗数据&#xff0c;帮企业建立能源管理体系&#xff0c;找到跑冒滴漏&#xff0c;从而为企业节能提供依据。 进一步为企业实现碳跟踪、碳盘查、碳交易、谈汇报的全生命过程。 为中国碳达峰-碳中和做出贡献。 针对客…

C++ AVLTree

目录 1. AVLTree的定义 2. 平衡因子 3. AVLTree的基础接口 插入 旋转 左单旋&#xff1a; 右单旋&#xff1a; 双旋&#xff1a; 4. AVLTree的测试 5. 小结 1. AVLTree的定义 二叉搜索树&#xff08;BST&#xff09;虽可以缩短查找的效率&#xff0c;但 如果数据有序…

Leetcode 在排序数组中查找元素的第一个和最后一个位置

这段代码的目的是在一个有序的数组中查找目标元素的第一个和最后一个位置。如果目标元素不存在&#xff0c;返回 [-1, -1]。算法要求时间复杂度为 O(log n)&#xff0c;所以使用了二分查找的思想。 主要思路&#xff1a; 使用两次二分查找&#xff1a; 第一次二分查找用于找到…