Mybatis(XML映射文件、动态SQL)

发布于:2025-06-18 ⋅ 阅读:(17) ⋅ 点赞:(0)

目录

 

基础操作

准备:

删除:

新增:

更新:

查询:

条件查询:

XML映射文件

动态SQL

if

foreach

sql&include


 

基础操作

准备:

准备数据库表

创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok)

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

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

准备Mapper接口

删除:

    @Delete("delete from teachnewstudent where id=#{id}")
    public void delete(Long id);
特别指出占位符 #{id}

删除是由返回值的,数据的返回值改为int即可删除数据

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

日志输出:

可以在application.properties中,打开mybatis的日志,并指定输出到控制台。

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

预编译SQL

优势:性能更高

更安全(防止SQL注入)

SQL注入:

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

新增:

 @Insert("insert into user(name,intro,state) values(#{name},#{intro},#{state}")
    public void insert(User user);

 如果有多个参数可使用实体类来封装多个参数

主键返回:

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

实现:加上注解@Options(框架会自动将生成的主键值,赋值给user对象的id属性)

    @Options(keyProperty="id", useGeneratedKeys = true)
    @Insert("insert into user(name,intro,state)+values(#{name},#{intro},#{state}")
    public void insert(User user);

更新:

一般是根据主键来修改(因为主键是不改变的)

    @Update("update user set name=#{name},intro=#{intro},state=#{state} where id=#{id}")
    public void update(User user);

查询:

根据id查询

   @Select("select * from user where id=#{id}")
    public User getById(Long id);

数据封装:

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

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

解决方案:

方案一:给字段起别名,让别名与实体类属性一致

  @Select("select id,name,create_time createTime,update_time updateTime from user where id=#{id}")
    public User getById(Long id);

方案二:通过@Results,@Result 注解手动映射封装

 @Results({
    @Result(column="",property="")

})
 @Select("select * from user where id=#{id}")
    public User getById(Long id);

 column为需要封装的字段,property为封装到的属性

方案三:开启mybatis的驼峰命名自动映射开关 即:a_ column------>aColumn

在application.properties配置mybatis.configuration.map-underscore-to-camel-case=true

需要严格遵守数据库名为下划线,类型名为驼峰命名

 

条件查询:

    @Select("select * from user where name like '%${name}%' and state=#{state}")
    public List<User> list1(String name,Short state);

因为#{}是预编译符不能出现在""之内所以需要用$符号来代替(所以存在问题性能低、不安全、存在SQL注入问题)

解决方法:concat  字符串拼接函数

    @Select("select * from user where name like concat('%',#{name},'%') and state=#{state}")
    public List<User> list1(String name,Short state);

 在springboot的2.x版本,参数名与注解中引用部分相同,否则需要单独加入注解

 

XML映射文件

规范:

XML映射文件的名称与Mapper接口名称一致,并且将XML映射文件和Mapper接口放置在相同包下(同包同名)。

XML映射文件的namespace属性为Mapper接口全限定名一致。

XML映射文件中sql语句的id与Mapper接口中的方法名一致,并保持返回类型一致。

目录使用/来分隔

约束:

官方文档:入门_MyBatis中文网

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.UserMapper">

</mapper>

namespace的属性值和接口全类名保持一致

<mapper namespace="com.example.demo.mapper.UserMapper">
    <select id="list" resultType="com.example.pojo.User">
        select * from user where name like
                '%${name}%' and state=#{state}
    </select>
</mapper>

 

 插件:MyBatisX(提高MyBatis效率)能够快速定位

 

动态SQL

动态SQL

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

 

if

<if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。

<mapper namespace="com.example.mapper.Usermapper">
    <select id="list" resultType="com.example.pojo.User">
        select * from user
            <where>
            <if test="name != null">
            name like'%${name}%'
            </if>
            <if test="state!= null">
             and state=#{state}
             </if>
              </where>
    </select>
</mapper>

where标签会自动去除多余的and关键字,而且会判断条件成不成立,当条件不成立时不会生成where关键字 而且会自动去除子句开头的AND或者OR

需求:动态更新员工信息,如果更新时传递有值,则更新;如果更新时没有传递值,则不更新。

在 if 中添加 test属性即可

<set>标签替换set关键字,能够去除掉多余的逗号

foreach

进行循环遍历的标签,通常用在批量删除中

属性:

collection:遍历的集合(与参数名保持一致)

item:遍历出来的元素

separator:分隔符

open:遍历开始前拼接的SQL片段

close:遍历结束后拼接的SQL片段

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

 

sql&include

sql负责抽取一个片段,而include引用一个片段进行复用

<sql id="commonSelect">
     select id,name
</sql>

include 的 refid属性负责指定你要引用哪个片段值,该值为select的id值

 查询一个表的全部字段时不建议使用select*,而是要罗列所有字段(select*性能较低)

<include refid="commonSelect"/>

 

 


网站公告

今日签到

点亮在社区的每一天
去签到