MyBatis

简介: MyBatis

MyBatis

Mybaits 是一个优秀的 持久层 框架, 用于简化 JDBC 开发

简单的说 : Mabatis 是更简单完成程序和数据库交互的框架, 也就是更简单的操作和读取数据库的工具

#{ } & ${ }

#{ } : 预编译 SQL

${ } : 即时 SQL

SQL 的执行流程

  1. 解析语法, 校验 SQL 有没有问题
  2. SQL 优化编译, 制定执行计划
  3. 执行SQL
  1. 性能区别 : 对于预编译 SQL, 在编译一次过后, 会将编译后的 SQL 语句缓存起来, 后面再次执行这条语句时, 不会重新编译 (只是替换参数), 省去了解析优化等过程, 因此可以提高性能
  2. SQL 注入 : 通过操作输入的数据来修改实现定义好的 SQL 语句, 以达到执行代码, 对服务器进行攻击. ${ } 存在 SQL 注入问题, #{ } 可以解决 SQL 注入问题.


${ } 的使用场景

  1. 排序 : select * from user order by id ${ };
  2. 模糊匹配 : like '%${key}%' – 可以使用内置函数 concat( ) 替代
  3. 分库分表传 表名

数据库连接池 – 池化技术

数据库连接池负责分配, 管理, 和释放数据库连接. 它允许应用程序重复使用一个现有的数据库连接, 而不是每次使用都要重新简历, 使用完毕就释放销毁.

作用 :

  1. 减少了网络开销
  2. 资源重用
  3. 提升了系统的性能

MyBatis 默认使用的数据库连接池是 Hikari .

数据库表和类对象的参数匹配

  1. SQL 语句中使用 as 起别名
  2. 结果映射
<resultMap id="userinfoMap" type="com.zrj.mybatisreview.model.UserInfo">
    <id column="id" property="id"></id>
    <result column="delete_flag" property="deleteFlag"></result>
    <result column="create_tiem" property="createTime"></result>
    <result column="update_time" property="updateTime"></result>
</resultMap>

<select id="queryAllUser" resultMap="userinfoMap">
    select * from userinfo
</select>

  1. 配置文件中开启 驼峰命名
    驼峰命名规则 : 表中字段: abc_xyz => 类对象属性 : abcXyz
mybatis:
  configuration:
    map-underscore-to-camel-case: true #配置驼峰⾃动转换

使用注释, 操作数据库

// 使用该注释获取数据库表中的主键, 并将其传输到 绑定类对象中的 keyProperty 属性中
@Options(useGeneratedKeys = true, keyProperty = "id")
@Select("Insert into user values(null, #{username}, #{password})")
public Integer insertOne(@Param("username") String username,@Param("password") String password);

@Delete("delete from user where id = #{id}")
public Integer delOne(int id);

@Select("select * from user order by id desc")
public List<User> selectAll();

@Update("update user set username = #{username} where id = #{id}")
public Integer updateOne(@Param("id") int id, @Param("username") String username);

使用 xml 文件, 操作数据库

<resultMap id="userinfoMap" type="com.zrj.mybatisreview.model.UserInfo">
  <id column="id" property="id"></id>
  <result column="delete_flag" property="deleteFlag"></result>
  <result column="create_tiem" property="createTime"></result>
  <result column="update_time" property="updateTime"></result>
</resultMap>

<select id="queryAllUser" resultMap="userinfoMap">
    select * from userinfo
</select>

<insert id="insertUserInfo" useGeneratedKeys="true" keyProperty="userinfo.id">
    insert into userinfo(username, password, age, gender, phone)
    values(#{userinfo.username}, #{userinfo.password},
    #{userinfo.age}, #{userinfo.gender},
    #{userinfo.phone})
</insert>

<update id="updateOne">
    update userinfo set username = #{username} where id = #{id}
</update>

<delete id="delOne">
    delete from user where id = #{id}
</delete>

Mybatis 中动态标签


< if > 标签

<select id="one">
    select
        (username, password,
        <if test="age != 0">
            age,
        </if>
        gender, phone)
    from user where id = #{id}
</select>


< trim > 标签

理论上其他标签都可以使用 trim 标签实现

<insert id="three" useGeneratedKeys="true" keyProperty="userinfo.id">
    insert into userinfo
        <trim prefix="(" suffix=")" suffixOverrides="," prefixOverrides=",">
            <if test="username != null">
                username,
            </if>
            <if test="password != null">
                `password`,
            </if>
        </trim>
    values
        <trim prefix="(" suffix=")" suffixOverrides="," prefixOverrides=",">
            <if test="username != null">
                #{username},
            </if>
            <if test="password != null">
                #{password},
            </if>
        </trim>
</insert>


< where > 标签

< where > 标签能够自动去除子句开头的 AND 或者 OR

< where > 只会在子元素有内容的情况下才插入 where 子句

<select id="two">
  select (username, password, age, gender, phone)
  from user
    <where>
      <if test="id != null">
        and id = #{id}
      </if>
      <if test="username != null">
        and `username` = #{username}
      </if>
      <if test="password != null">
        and `password` = #{password}
      </if>
   </where>
</select>

< set > 标签

< set > 标签能够自动删除 额外的逗号

<update id="four">
    update userinfo 
    <set>
        <if test="username != null">
            username = #{username} ,
        </if>

        <if test="password != null">
            `password` = #{password},
        </if>
    </set>
    where id = 1
</update>

< foreach > 标签

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



< sql > 标签 & < include > 标签

< sql > 标签 : 定义可重用代码片段

< include > 标签 : 通过 refid 属性, 绑定要包含的代码片段

<select id="six1">
    select username, password, age, gender, phone
    from user
</select>

<sql id="e">
    username, password, age, gender, phone
</sql>

<select id="six2">
    select (
    <include refid="e"></include>
    )
    from user
</select>

目录
相关文章
|
6月前
|
设计模式 消息中间件 监控
并发设计模式实战系列(5):生产者/消费者
🌟 ​大家好,我是摘星!​ 🌟今天为大家带来的是并发设计模式实战系列,第五章,废话不多说直接开始~
217 1
|
消息中间件 存储 Java
📨 Spring Boot 3 整合 MQ 构建聊天消息存储系统
本文详细介绍了如何使用Spring Boot 3结合RabbitMQ构建高效可靠的聊天消息存储系统。通过引入消息队列,实现了聊天功能与消息存储的解耦,解决了高并发场景下直接写入数据库带来的性能瓶颈问题。文章首先分析了不同MQ产品的特点及适用场景,最终选择RabbitMQ作为解决方案,因其成熟稳定、灵活路由和易于集成等优势。接着,通过Docker快速部署RabbitMQ,并完成Spring Boot项目的配置与代码实现,包括生产者发送消息、消费者接收并处理消息等功能。最后,通过异步存储机制,既保证了消息的即时性,又实现了可靠持久化。
572 0
📨 Spring Boot 3 整合 MQ 构建聊天消息存储系统
|
消息中间件
【面试问题】如何确保消息正确地发送至 RabbitMQ? 如何确保消息接收方消费了消息?
【1月更文挑战第27天】【面试问题】如何确保消息正确地发送至 RabbitMQ? 如何确保消息接收方消费了消息?
|
消息中间件 存储 Java
MQ核心作用、解耦、削峰使用场景详解
【11月更文挑战第21天】在如今的高并发互联网应用中,如何确保系统在巨大的流量冲击下还能稳定运行,是每个技术团队都会遇到的挑战。说到这,消息队列(MQ)就是背后的“大功臣”了。无论是异步处理请求、平滑应对流量高峰,还是让各个系统模块相互独立不“拖后腿”,MQ都是不可或缺的帮手。那么,MQ是如何削峰的?或者它是如何让复杂系统解耦的?今天,我们就来聊聊MQ的三大核心功能,看它是如何助力系统高效、稳定运转的。
725 1
|
Kubernetes jenkins 持续交付
Jenkins + SVN/Git + Maven + Docker + 阿里云镜像 + Kubernetes(K8S)
Jenkins + SVN/Git + Maven + Docker + 阿里云镜像 + Kubernetes(K8S)
582 0
|
安全 Java 物联网
Java在物联网应用中的实际应用
Java在物联网应用中的实际应用
|
缓存 NoSQL 关系型数据库
【中间件】Redis与MySQL双写一致性如何保证?--缓存和数据库在双写场景下一致性是如何保证的
【中间件】Redis与MySQL双写一致性如何保证?--缓存和数据库在双写场景下一致性是如何保证的
643 0
【中间件】Redis与MySQL双写一致性如何保证?--缓存和数据库在双写场景下一致性是如何保证的
|
NoSQL 网络安全 Redis
Redis 搭建主从集群
Redis 搭建主从集群
148 0
|
消息中间件 存储 Kafka
几种 MQ 顺序消息的实现方式
几种 MQ 顺序消息的实现方式
|
JSON 前端开发 数据库
SpringSecurity实现前后端分离登录授权详解
在介绍完SpringSecurity实现前后端分离认证之后,然后就是SpringSecurity授权,在阅读本文章之前可以先了解一下作者的上一篇文章SpringSecurity认证SpringSecurity实现前后端分离登录token认证详解_山河亦问安的博客-CSDN博客。
405 0