北冰洋以北 发表于 2024-11-1 09:07:09

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

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

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



[*]准备数据库表 emp
[*]创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)
https://i-blog.csdnimg.cn/direct/9a9017c9b65c488a9bd41a87c1358a31.png
https://i-blog.csdnimg.cn/direct/b1bbe89fede846a6ab62e149d005be0b.png
 


[*]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 {
}
 根据主键删除

https://i-blog.csdnimg.cn/direct/ed269df614bd4dfe9eb3598c33ea29ea.png


[*]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
 https://i-blog.csdnimg.cn/direct/77f39c1093cb4a46a7b38f8e9e862a9f.png
https://i-blog.csdnimg.cn/direct/43c095ae520b4a1eb23f478ec88d610d.png 预编译SQL

   优点:


[*]性能更高
[*]更安全(防止SQL注入)
https://i-blog.csdnimg.cn/direct/c6de550713f449169b0f16dc81f7184c.png
 SQL注入

SQL注入是通过操作输入的数据来修改事先定义好的SQL语句,以达到实验代码对服务器举行攻击的方法。
https://i-blog.csdnimg.cn/direct/99c283adb93b46c49a67c2259153097a.png 参数占位符

    #{…}


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


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

https://i-blog.csdnimg.cn/direct/c08d6f903e8e4522892413320d75fa21.png
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);
主键返回 

https://i-blog.csdnimg.cn/direct/5b77b0c727c54fc99be193642d544cac.png
描述:
在数据添加乐成后,需要获取插入数据库数据的主键。如:添加套餐数据时,还需要维护套餐菜品关系表数据。
实现:
@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);
更新

 
https://i-blog.csdnimg.cn/direct/b233928ac35849d6baf8a782fb4a1808.png
 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查询)

https://i-blog.csdnimg.cn/direct/0b5ad438281a4f0dba6324393d048a8b.png
SQL语句
select *from emp where id = 19;
 接口方法
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);
https://i-blog.csdnimg.cn/direct/ea28cdac95794cd8aaa5ddf0ab8709d1.png

 数据封装 



[*]实体类属性名 和 数据库表查询返回的字段名同等,mybatis会自动封装。
[*]假如实体类属性名 和 数据库表查询返回的字段名不同等,不能自动封装。
https://i-blog.csdnimg.cn/direct/f57808288c834e469e7f07ac0c326315.png
https://i-blog.csdnimg.cn/direct/dfc218387cca4b95ab11f4acce076c00.png


[*] 起别名:在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;
接口方法
https://i-blog.csdnimg.cn/direct/fef943893fd24141accfc12692710d88.png
@Select("select * from emp where name likeconcat('%',#{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版本
https://i-blog.csdnimg.cn/direct/3958262f09614c789ae28cab8eb29954.png 


[*]在springBoot的1.x版本/单独使用mybatis
https://i-blog.csdnimg.cn/direct/a0ba553faf6948afa475e6efaccd1880.png
 XML映射文件

   规范:


[*]XML映射文件的名称与Mapper接口名称同等,而且将XML映射文件和Mapper接口放置在相同包下(同包同名)。
[*]XML映射文件的namespace属性为Mapper接口全限定名同等。
[*]XML映射文件中sql语句的id与Mapper 接口中的方法名同等,并保持返回范例同等。
https://i-blog.csdnimg.cn/direct/865a07b7a29e4f579adeeece480d8d0c.png
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的插件,为效率而生。
https://i-blog.csdnimg.cn/direct/a47b80f7eb66438784a231d67a997cf8.png
 使用Mybatis的注解,重要是来完成一些简单的增删改查功能。假如需要实现复杂的SQL功能,建议使用XML来配置映射语句。
Mybatis动态SQL

随着用户的输入或外部条件的变革而变革的SQL语句,我们称为 动态SQL。
https://i-blog.csdnimg.cn/direct/99cefae4d728477e807a3bd245906377.png
https://i-blog.csdnimg.cn/direct/e8c24a14d4434ee0a488a15b44b2ebfd.png
https://i-blog.csdnimg.cn/direct/803b10ecb37e48158ed34c80861e00e9.png
<if>



[*]<if>:用于判定条件是否成立。使用test属性举行条件判定,假如条件为true,则拼接SQL。
[*]<where>:where 元素只会在子元素有内容的情况下才插入where子句。而且会自动去除子句的开头的AND 或OR。
https://i-blog.csdnimg.cn/direct/976c0e20e7374458bc08c39f73f8ea7e.png
<set>:动态地在行首插入 SET 关键字,并会删掉额外的逗号。(用在update语句中)
<foreach>

https://i-blog.csdnimg.cn/direct/6ad63080c8754aa082916db428e1b76f.png
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片断。
https://i-blog.csdnimg.cn/direct/9d1c7750501f48fda4ce4168ab148d5f.png 
总结

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

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: MyBatis 基础知识:配置文件、映射器与 SQL 示例详解