本篇博客将深入探讨 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
- public interface EmpMapper {
- }
复制代码 根据主键删除
- 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语句
- 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的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 的机动性和易用性将为数据恒久化提供强有力的支持。盼望这篇博客对你有所帮助,鼓励你深入探索更多高级功能!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |