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

打印 上一主题 下一主题

主题 900|帖子 900|积分 2700

本篇博客将深入探讨 MyBatis 的基础知识,包罗配置文件的设置、映射器的使用以及实际的 SQL 示例。
  文章目次
前言
准备工作
 根据主键删除
日志输出
​编辑 预编译SQL
 SQL注入
​编辑 参数占位符
 新增员工
主键返回 
更新
查询(根据ID查询)
​编辑
 数据封装 
 查询(条件查询)
参数名说明
 XML映射文件
Mybatis动态SQL
        sql片断
总结

前言

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

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



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


 


  • application.properties中引入数据库毗连信息
  1. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
  3. spring.datasource.username=root
  4. spring.datasource.password=1234
复制代码


  • 创建对应的实体类 Emp(实体类属性采用驼峰定名)
  1. @Data
  2. public class Emp {
  3.     private Integer id;
  4.     private String username;
  5.     private String password;
  6.     private String name;
  7.     private Short gender;
  8.     private String image;
  9.     private Short job;
  10.     private LocalDate entrydate;
  11.     private Integer deptId;
  12.     private LocalDateTime createTime;
  13.     private LocalDateTime updateTime;
  14. }
复制代码


  • 准备Mapper接口 EmpMapper
  1. @Mapper
  2. public interface EmpMapper {
  3. }
复制代码
 根据主键删除




  • SQL语句 
  1. delete from emp where id = 17;
复制代码


  • 接口方法
  1. @Delete("delete from emp where id = #{id}")public void delete(Integer id);
复制代码
  注意事项:
  假如mapper接口方法形参只有一个平凡范例的参数,#{…} 里面的属性名可以随便写,如:#{id}、#{value}。 
  日志输出



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

 预编译SQL


   优点:
  

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

 SQL注入

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


    #{…}
  

  • 实验SQL时,会将#{…}替换为?,天生预编译SQL,会自动设置参数值。
  • 使用机遇:参数转达,都使用#{…}
    ${…}
  

  • 拼接SQL。直接将参数拼接在SQL语句中,存在SQL注入题目。
  • 使用机遇:假如对表名、列表举行动态设置时使用。 
   新增员工


SQL语句
  1. 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');
复制代码
 接口方法:
  1. @Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) " +
  2.         "values(#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")
  3. public void insert(Emp emp);
复制代码
主键返回 


描述:
在数据添加乐成后,需要获取插入数据库数据的主键。如:添加套餐数据时,还需要维护套餐菜品关系表数据。
实现:
  1. @Options(keyProperty = "id", useGeneratedKeys = true)@Insert("insert into emp(username, name, gender, image, job, entrydate, dept_id, create_time, update_time) " +
  2.         "values(#{username}, #{name}, #{gender}, #{image}, #{job}, #{entrydate}, #{deptId}, #{createTime}, #{updateTime})")
  3. public void insert(Emp emp);
复制代码
更新

 

 SQL语句(根据ID更新员工信息)
  1. 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;
复制代码
接口方法
  1. @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}")
  2. public void update(Emp emp);
复制代码
查询(根据ID查询)


SQL语句
  1. select *  from emp where id = 19;
复制代码
 接口方法
  1. @Select("select * from emp where id = #{id}")
  2. public Emp getById(Integer id);
复制代码


 数据封装 



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




  •  起别名:在SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。
  1. @Select("select id, username, password, name, gender, image, job, entrydate, dept_id deptId, create_time createTime, update_time updateTime from emp where id = #{id} ")
  2. public Emp getById(Integer id);
复制代码


  • 手动结果映射:通过 @Results及@Result 举行手动结果映射 
  1. @Select("select * from emp where id = #{id}")@Results({
  2.         @Result(column = "dept_id", property = "deptId"),
  3.         @Result(column = "create_time", property = "createTime"),
  4.         @Result(column = "update_time", property = "updateTime"))
  5. public Emp getById(Integer id);
复制代码


  • 开启驼峰定名:假如字段名与属性名符合驼峰定名规则,mybatis会自动通过驼峰定名规则映射。 
  1. #开启驼峰命名自动映射,即从数据库字段名 a_column 映射到Java 属性名 aColumn。
  2. mybatis.configuration.map-underscore-to-camel-case=true
复制代码
 查询(条件查询)

SQL语句
  1. select *  from emp where name like '%张%' and gender = 1 and entrydate between '2010-01-01' and '2020-01-01 ' order by update_time desc;
复制代码
接口方法

  1. @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接口:
  1. @Mapper
  2. public interface EmpMapper {
  3.       public List<Emp> list (String name, Short gender , LocalDate begin , LocalDate end);
  4. }
复制代码
 XML映射文件
  1. <mapper namespace="itheima">
  2.     <select id="abc" resultType="com.itheima.pojo.Emp">
  3.         select * from emp where name like concat('%',#{name},'%') and gender = #{gender}
  4.                       and entrydate between #{begin} and #{end} order by update_time desc
  5.     </select>
  6. </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语句
  1. delete from emp where id in (1,2,3);
复制代码
接口方法
  1. //批量删除
  2. public void deleteByIds(List<Integer>  ids);
复制代码
XML映射文件
  1. <delete id="deleteByIds">
  2.     delete from emp where id in    <foreach collection="ids" item="id" separator="," open="(" close=")">
  3.         #{id}
  4.     </foreach>
  5. </delete>
复制代码
  属性:
  

  • collection:聚集名称
  • item:聚集遍历出来的元素/项
  • separator:每一次遍历使用的分隔符
  • open:遍历开始前拼接的片断
  • close:遍历竣事后拼接的片断
   sql片断



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

总结

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

北冰洋以北

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表