首页 > 其他分享 >mybaits相关基础

mybaits相关基础

时间:2024-09-11 22:52:14浏览次数:3  
标签:Mapper name gender 基础 mybaits emp SQL 相关 id

1.配置文件

application.properties:

#驱动类名称
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#数据库连接的url
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis
#连接数据库的用户名
spring.datasource.username=root
#连接数据库的密码
spring.datasource.password=1234

UserMapper:

import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;

@Mapper
public interface UserMapper {
    
    //查询所有用户数据
    @Select("select id, name, age, gender, phone from user")
    public List<User> list();
    
}

@Mapper注解:表示是mybatis中的Mapper接口

  • 程序运行时:框架会自动生成接口的实现类对象(代理对象),并给交Spring的IOC容器管理

@Select注解:代表的就是select查询,用于书写select查询语句

2.Druid连接池依赖

  1. 在pom.xml文件中引入依赖
<dependency>
    <!-- Druid连接池依赖 -->
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.8</version>
</dependency>
  1. 在application.properties中引入数据库连接配置

方式1:

spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.url=jdbc:mysql://localhost:3306/mybatis
spring.datasource.druid.username=root
spring.datasource.druid.password=1234

方式2:

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

3.@Mapper 注解

/*@Mapper注解:表示当前接口为mybatis中的Mapper接口
  程序运行时会自动创建接口的实现类对象(代理对象),并交给Spring的IOC容器管理
*/
@Mapper
public interface EmpMapper {

}

4. 日志输入

在Mybatis当中我们可以借助日志,查看到sql语句的执行、执行传递的参数以及执行结果。具体操作如下:

  1. 打开application.properties文件

  2. 开启mybatis的日志,并指定输出到控制台

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

5.增删改查

@Mapper
public interface EmpMapper {
   
   //会自动将生成的主键值,赋值给emp对象的id属性
   @Options(useGeneratedKeys = true,keyProperty = "id")
   @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);


    @Delete("delete from emp where id = #{id}")//使用#{key}方式获取方法中的参数值
   	public void delete(Integer id);

   
    @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);
   
	@Select("select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp where id=#{id}")
    public Emp getById(Integer id);


}

开启驼峰命名(推荐):如果字段名与属性名符合驼峰命名规则,mybatis会自动通过驼峰命名规则映射

驼峰命名规则: abc_xyz => abcXyz

  • 表中字段名:abc_xyz
  • 类中属性名:abcXyz
# 在application.properties中添加:
mybatis.configuration.map-underscore-to-camel-case=true
模糊匹配
  • 使用MySQL提供的字符串拼接函数:concat(‘%’ , ‘关键字’ , ‘%’)
@Mapper
public interface EmpMapper {

    @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);

}

6.Mybatis的XML配置文件

6.1 XML配置文件规范

使用Mybatis的注解方式,主要是来完成一些简单的增删改查功能。如果需要实现复杂的SQL功能,建议使用XML来配置映射语句,也就是将SQL语句写在XML配置文件中。

在Mybatis中使用XML映射文件方式开发,需要符合一定的规范:

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

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

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

在这里插入图片描述

<select>标签:就是用于编写select查询语句的。

  • resultType属性,指的是查询返回的单条记录所封装的类型。
6.2 XML配置文件实现

xml映射文件中的dtd约束,直接从mybatis官网复制即可

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
 <!--查询操作-->
    <select id="list" 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>

配置:XML映射文件的namespace属性为Mapper接口全限定名

7. Mybatis动态SQL

7.1 动态SQL-if where set

<if>:用于判断条件是否成立。使用test属性进行条件判断,如果条件为true,则拼接SQL。
-<where>只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR

<select id="list" resultType="com.itheima.pojo.Emp">
        select * from emp
        <where>
             <!-- if做为where标签的子元素 -->
             <if test="name != null">
                 and name like concat('%',#{name},'%')
             </if>
             <if test="gender != null">
                 and gender = #{gender}
             </if>
             <if test="begin != null and end != null">
                 and entrydate between #{begin} and #{end}
             </if>
        </where>
        order by update_time desc
</select>

<set>:动态的在SQL语句中插入set关键字,并会删掉额外的逗号。(用于update语句中)

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

    <!--更新操作-->
    <update id="update">
        update emp
        <!-- 使用set标签,代替update语句中的set关键字 -->
        <set>
            <if test="username != null">
                username=#{username},
            </if>
            <if test="name != null">
                name=#{name},
            </if>
            <if test="gender != null">
                gender=#{gender},
            </if>
            <if test="image != null">
                image=#{image},
            </if>
            <if test="job != null">
                job=#{job},
            </if>
            <if test="entrydate != null">
                entrydate=#{entrydate},
            </if>
            <if test="deptId != null">
                dept_id=#{deptId},
            </if>
            <if test="updateTime != null">
                update_time=#{updateTime}
            </if>
        </set>
        where id=#{id}
    </update>
</mapper>

小结

  • <if>
    • 用于判断条件是否成立,如果条件为true,则拼接SQL
    • 形式:
      <if test="name != null"> … </if>
      
  • <where>
    • where元素只会在子元素有内容的情况下才插入where子句,而且会自动去除子句的开头的AND或OR
  • <set>
    • 动态地在行首插入 SET 关键字,并会删掉额外的逗号。(用在update语句中)
7.2 动态SQL-foreach

SQL语句:

delete from emp where id in (1,2,3);

Mapper接口:

@Mapper
public interface EmpMapper {
    //批量删除
    public void deleteByIds(List<Integer> ids);
}

XML映射文件:

  • 使用<foreach>遍历deleteByIds方法中传递的参数ids集合
<foreach collection="集合名称" item="集合遍历出来的元素/项" separator="每一次遍历使用的分隔符" 
         open="遍历开始前拼接的片段" close="遍历结束后拼接的片段">
</foreach>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.mapper.EmpMapper">
    <!--删除操作-->
    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
</mapper> 
7.4 动态SQL-sql&include

在xml映射文件中配置的SQL,有时可能会存在很多重复的片段,此时就会存在很多冗余的代码
我们可以对重复的代码片段进行抽取,将其通过标签封装到一个SQL片段,然后再通过标签进行引用。

  • <sql>:定义可重用的SQL片段

  • <include>:通过属性refid,指定包含的SQL片段

SQL片段: 抽取重复的代码

<sql id="commonSelect">
 	select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time from emp
</sql>

然后通过<include> 标签在原来抽取的地方进行引用。操作如下:

<select id="list" resultType="com.itheima.pojo.Emp">
    <include refid="commonSelect"/>
    <where>
        <if test="name != null">
            name like concat('%',#{name},'%')
        </if>
        <if test="gender != null">
            and gender = #{gender}
        </if>
        <if test="begin != null and end != null">
            and entrydate between #{begin} and #{end}
        </if>
    </where>
    order by update_time desc
</select>

标签:Mapper,name,gender,基础,mybaits,emp,SQL,相关,id
From: https://blog.csdn.net/songguojiebd/article/details/142151879

相关文章

  • 第一章 网页制作的基础知识
                    1.1 认识网页和网站1.1.1网页、网站网页和网站的区别:网页:网页是由HTML编写,通过WWW网传输,且被浏览器编译后供用户获取信息的页面文件,又称为Web页。网站:网站是多个网页的集合常用术语:Internet、WWW、浏览器、URL、IP、域......
  • 如何系统的从0到1学习大模型?相关书籍及课程那些比较好?
    要系统地从0到1学习大模型,需要一个全面的学习计划和有效的资源。以下是我为你推荐的学习路径和相关资源。1.基础理论大模型的基础是机器学习和深度学习。因此,你首先需要掌握这些领域的基础知识。推荐以下书籍和课程:书籍:《PatternRecognitionandMachineLearning》byC......
  • WPS表格/文字/演示教程零基础全套网盘资源分享
    随着互联网和计算机的普及,办公软件越来越流行。不管是职场打工人还是学生党,基本上都要接触或使用办公软件。常用的办公软件有Office与WPS,今天我们一起来聊聊后者。WPS相对来说是比较容易上手的办公软件,尤其是对于有一定计算机基础的用户。通过观看视频教程和动手操作,可以较快......
  • 【网络安全】基础知识详解(非常详细)零基础入门到精通
    一、什么是网络安全?百度上对“网络安全”是这么介绍的:“网络安全是指网络系统的硬件、软件及其系统中的数据受到保护,不因偶然的或者恶意的原因而遭受到破坏、更改、泄露、系统连续可靠正常地运行,网络服务不中断。”嗯…是不是感觉有点抽象。那么我们再换一种表述:网络安......
  • Python基础
    目录1.常见字面量2.Python中的注释3.Python中的变量变量是什么?及作用?变量的格式?变量的特征?4.Python中查看数据的数据类型5.Python数据类型的转换(字符串,整数,浮点数)6.Python中的标识符1.用户编写代码时,对变量.类.方法等编写的名字,叫做标识符.2.标识符命名......
  • 数据处理与统计分析篇-day01-Linux基础与环境搭建
    day01-Linux基础计算机简介概述电子计算机,电脑,PC,Computer,就是由软件+硬件组成的电子设备.组成计算机硬件CPU(运算器,控制器)存储器(内存,外存)输入设备输出设备计算机软件系统软件:充当用户和计算机硬件之间的桥梁的.PC端:windows,......
  • 面试-JS基础-异步和单线程
    同步和异步的区别是什么?手写Promise加载一张图片前端用到异步的场景?JS是单线程语言,只能同时做一件事浏览器和nodejs已支持JS启动线程,比如WebWorker(不知道是啥东西)JS和DOM渲染共用一个线程,因为JS可以修改DOM结构。意味着JS在工作的时候DOM渲染要停止,反之亦然。异步的出......
  • 神经网络基础
      神经网络组件 :简单神经元;多层神经元;前馈神经网络;非线性等。如何训练 :目标;梯度;反向传播。词表示:Word2Vec:常见的神经网络 :RNN(循环神经网络) :序列记忆;语言模型。RNN的梯度问题。变体:GRU;LSTM;双向RNN。CNN(卷积神经网络) :NLP流水线教程(PyTorch)......
  • 0基础开始Pine量化 止盈改进策略(附代码)
    0基础开始Pine量化止盈改进策略(附代码)可以先看前面文章里涉及到的策略https://www.cnblogs.com/Mephostopheles/p/18406658什么是止盈止盈的核心思想:当市场价格达到设定的目标后,投资者会卖出资产,防止市场波动将已经取得的利润变为损失。通过止盈,投资者在确保一定盈利的情况......
  • --优质Java基础练习-- 采取控制台方式书写简单学生管理系统【升级版本(含注册登录功能)
    目录前言     该项目涉及的知识点项目准备 JDK编程工具Idea 需求文档-升级部分(参考黑马程序员)学生管理系统升级版需求分析登录界面用户类注册功能登录功能忘记密码验证码规则需求分析 编码新建项目-StudentManagementStudent类User类 核心方......