当前位置: 首页 > article >正文

MyBatis 基础知识:配置文件、映射器与 SQL 示例详解

本篇博客将深入探讨 MyBatis 的基础知识,包括配置文件的设置、映射器的使用以及实际的 SQL 示例。

文章目录

前言

准备工作

 根据主键删除

日志输出

​编辑 预编译SQL

 SQL注入

​编辑 参数占位符

 新增员工

主键返回 

更新

查询(根据ID查询)

​编辑

 数据封装 

 查询(条件查询)

参数名说明

 XML映射文件

Mybatis动态SQL

        sql片段

总结


前言

本篇博客将深入探讨 MyBatis 的基础知识,包括配置文件的设置、映射器的使用以及实际的 SQL 示例。我们将逐步讲解如何配置 MyBatis,如何定义和使用映射器,以及如何执行 SQL 操作,以便帮助读者快速上手并掌握这一强大工具。


提示:以下是本篇文章正文内容,下面案例可供参考

准备工作

  • 准备数据库表 emp
  • 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)

 

  • application.properties中引入数据库连接信息
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=1234
  • 创建对应的实体类 Emp(实体类属性采用驼峰命名)
@Data
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 deptId;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}
  • 准备Mapper接口 EmpMapper
@Mapper
public interface EmpMapper {
}

 根据主键删除

  • SQL语句 
delete from emp where id = 17;
  • 接口方法
@Delete("delete from emp where id = #{id}")public void delete(Integer id);

注意事项:

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

日志输出

  •  可以在application.properties中,打开mybatis的日志,并指定输出到控制台。
#指定mybatis输出日志的位置,输出控制台
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl

 

 预编译SQL

优点:

  • 性能更高
  • 更安全(防止SQL注入)

 SQL注入

SQL注入是通过操作输入的数据来修改事先定义好的SQL语句,以达到执行代码对服务器进行攻击的方法。

 参数占位符

 #{…}

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

${…}

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

 新增员工

SQL语句

insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) values ('songyuanqiao','宋远桥',1,'1.jpg',2,'2012-10-09',2,'2022-10-01 10:00:00','2022-10-01 10:00:00');

 接口方法:

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

主键返回 

描述:

在数据添加成功后,需要获取插入数据库数据的主键。如:添加套餐数据时,还需要维护套餐菜品关系表数据。

实现:

@Options(keyProperty = "id", useGeneratedKeys = true)
@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);

更新

 

 SQL语句(根据ID更新员工信息)

update emp set username = 'songdaxia', name = '宋大侠', gender = 1 , image = '1.jpg' , job = 2, entrydate = '2012-01-01', dept_id = 2, update_time = '2022-10-01 12:12:12' where id = 19;

接口方法

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

查询(根据ID查询)

SQL语句

select *  from emp where id = 19;

 接口方法

@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);

 数据封装 

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

  •  起别名:在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);
  • 手动结果映射:通过 @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);
  • 开启驼峰命名:如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射。 
#开启驼峰命名自动映射,即从数据库字段名 a_column 映射到Java 属性名 aColumn。
mybatis.configuration.map-underscore-to-camel-case=true

 查询(条件查询)

SQL语句

select *  from emp where name like '%张%' and gender = 1 and entrydate between '2010-01-01' and '2020-01-01 ' order by update_time desc;

接口方法

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

 (推荐)

参数名说明

  • 在springBoot的2.x版本

 

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

 XML映射文件

规范:

  • XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)。
  • XML映射文件的namespace属性为Mapper接口全限定名一致。
  • XML映射文件中sql语句的id与Mapper 接口中的方法名一致,并保持返回类型一致。

Mapper接口:

@Mapper
public interface EmpMapper {
      public List<Emp> list (String name, Short gender , LocalDate begin , LocalDate end);
}

 XML映射文件

<mapper namespace="itheima">
    <select id="abc" 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>
</mapper>

 注:MybatisX 是一款基于 IDEA 的快速开发Mybatis的插件,为效率而生。

 使用Mybatis的注解,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句。

Mybatis动态SQL

随着用户的输入或外部条件的变化而变化的SQL语句,我们称为 动态SQL。

<if>

  • <if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。
  • <where>:where 元素只会在子元素有内容的情况下才插入where子句。而且会自动去除子句的开头的AND 或OR。

<set>:动态地在行首插入 SET 关键字,并会删掉额外的逗号。(用在update语句中)

<foreach>

SQL语句

delete from emp where id in (1,2,3);

接口方法

//批量删除
public void deleteByIds(List<Integer>  ids);

XML映射文件

<delete id="deleteByIds">
    delete from emp where id in    <foreach collection="ids" item="id" separator="," open="(" close=")">
        #{id}
    </foreach>
</delete>

属性:

  • collection:集合名称
  • item:集合遍历出来的元素/项
  • separator:每一次遍历使用的分隔符
  • open:遍历开始前拼接的片段
  • close:遍历结束后拼接的片段

 sql片段

  • <sql>:定义可重用的 SQL 片段。
  •  <include>:通过属性refid,指定包含的sql片段。

 


总结

通过这些内容,我们希望能帮助读者快速掌握 MyBatis 的基础知识,进而在实际项目中灵活应用。 MyBatis 的灵活性和易用性将为数据持久化提供强有力的支持。希望这篇博客对你有所帮助,激励你深入探索更多高级功能!


http://www.kler.cn/news/362710.html

相关文章:

  • 2 两数相加
  • 基于泊松洞过程建模的异构蜂窝网络信干比增益与近似覆盖率分析
  • 2.1 > Shell 是什么、如何更熟练的使用 Bash Shell
  • 论当前的云计算
  • AnaTraf | 网络性能监控系统NPM:提升网络性能与业务连续性
  • Visual Studio Code
  • 智能体时代:重塑人机交互的未来
  • 力扣刷题(sql)--零散知识点(1)
  • 恺撒密码简单实例
  • C语言程序设计:现代设计方法习题笔记《chapter3》
  • PyTorch求导相关
  • Eclipse Java 构建路径
  • ROS的导航功能包navfn中计算单元格的势值的原理介绍
  • 自动化抖音点赞取消脚本批量处理
  • 记一次真实项目的性能问题诊断、优化(阿里云redis分片带宽限制问题)过程
  • 富格林:严防欺诈漏洞安全交易
  • JVM(HotSpot):GC之垃圾回收器的分类
  • 2024年9月青少年软件编程(C语言/C++)等级考试试卷(三级)
  • 047_python基于Hadoop的租房数据分析系统的设计与实现
  • WRB Hidden Gap,WRB隐藏缺口,MetaTrader 免费公式!(指标教程)
  • 【数据结构】二叉树遍历(前序/中序/后序/层序-递归与非递归)
  • 开源呼叫中心系统与商业软件的对比
  • Vue 3 中实现自定义 404 页面的三种方法
  • Tips--解决更新resource.qrc之后新的资源无法加载的问题
  • C#,自动驾驶技术,ASAM OpenDRIVE BS 1.8.0 规范摘要与C# .NET Parser
  • HTML、CSS 和 JavaScript 的介绍