Web学习day04

news2024/9/23 5:25:09

mybatis


目录

mybatis

文章目录

一、查询

1.1结果映射

1.2多条件查询

1.3模糊查询

二、XML

书写规范

三、动态SQL

四、配置文件

4.1settings标签

4.2mappers标签

4.3environments标签

五、案例

5.1数据表

5.2实现类

5.3mapper实现

5.4工具类实现

5.5XML动态SQL实现

5.6XML配置实现

5.7测试实现

5.8pom.xml配置

总结


一、查询

1.1结果映射

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

字段起别名:SQL语句中,对不一样的列名起别名,别名和实体类属性名一样。

@Results @Result:通过 @Results@Result 进行手动结果映射。

1.2多条件查询

@Param 标注在方法参数的前面,用于声明参数在#{}中的名字

1.3模糊查询

${}性能低,不安全,存在SQL注入问题:

#{}推荐:

二、XML

书写规范

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

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

XML文件中sql语句的id与Mapper 接口中的方法名一致。

XML文件中sql语句的返回类型与Mapper 接口中的方法返回类型一致。

三、动态SQL

<if>

用于判断条件是否成立,如果条件为true,则拼接SQL

<where>

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

而且会自动去除子句的开头的AND OR

<set>

动态地在行首插入SET关键字,并会删掉额外的逗号(用在update语句中)

<foreach >

用来批量处理的 比如批量删除拼接 in后面的值

<sql>

定义一个sql片段 就是提取公共的sql

<include>

引入sql片段

四、配置文件

4.1settings标签

控制一些全局配置项的开闭

4.2mappers标签

加载Mapper接口位置

4.3environments标签

Druid(德鲁伊):  阿里巴巴提供的数据库连接池技术,国内使用率很高,提供了完善的监控机制

HikariCP:  日本人开发的连接池技术,号称性能之王,速度最快,SpringBoot2.0默认使用此连接池

五、案例

5.1数据表

5.2实现类

代码如下(示例):

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDate;
import java.time.LocalDateTime;

@Data
@NoArgsConstructor
@AllArgsConstructor
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 ed;

    private Integer deptId;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;
}

5.3mapper实现

代码如下:

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

public interface EmpMapper {

    @Select("select * from emp")
    public List<Emp> findAll();

    @Select("select * from emp")
    public List<Emp> findAll1();

    @Select("select id,username,password,name,gender,image,job,entrydate ed,dept_id,create_time,update_time from emp")
    public List<Emp> findAll2();

    @Select("select * from emp")
    @Results({
            @Result(column = "entrydate",property = "ed")
    })
    public List<Emp> findAll3();

    @Select("select * from emp where name =#{name} and gender = #{gender} and entrydate between #{begin} and #{end} ")
    @Results({
            @Result(column = "entrydate",property = "ed")
    })
    public List<Emp> findByCondition(@Param("name") String name,@Param("gender") Integer gender,@Param("begin") LocalDate begin,@Param("end") LocalDate end);

    @Select("select * from emp where name like concat('%',#{name},'%') and gender = #{gender} and entrydate between #{begin} and #{end} ")
    @Results({
            @Result(column = "entrydate",property = "ed")
    })
    public List<Emp> findByCondition2(@Param("name") String name,@Param("gender") Integer gender,@Param("begin") LocalDate begin,@Param("end") LocalDate end);

    public Emp findById(Integer id);

    List<Emp> findByCondition3(@Param("name") String name,@Param("gender") Short gender,@Param("begin") LocalDate begin,@Param("end") LocalDate end);
    
    void update(Emp emp);

    void deleteByIds(@Param("ids") List<Integer> ids);
}

5.4工具类实现

代码如下:

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory = null;

    //保证SqlSessionFactory仅仅创建一次
    static {
        try {
            //读取配置文件
            InputStream stream = Resources.getResourceAsStream("SqlMapConfig.xml");
            //创建SqlSessionFactory
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(stream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取sqlSession
    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }

    //提交事务 关闭sqlSession
    public static void close(SqlSession sqlSession) {
        if (sqlSession != null) {
            //提交事务
            sqlSession.commit();
            //释放资源
            sqlSession.close();
        }
    }
}

5.5XML动态SQL实现

代码如下:

<?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.itheima.mapper.EmpMapper">

    <sql id="mySql">
        select * from emp
    </sql>

    <resultMap id="MyMap" type="com.itheima.domain.Emp">
        <result column="entrydate" property="ed"/>
    </resultMap>
    <select id="findById" resultMap="MyMap">
        <include refid="mySql"/>
        where id = #{id}
    </select>


    <select id="findByCondition3" resultType="com.itheima.domain.Emp">
        <include refid="mySql"/>
        <where>
            <if test="name != null and name !=''">
                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>
    </select>

    <update id="update">
        update emp
        <set>
            <if test="username != null and username != ''">
                username = #{username},
            </if>
            <if test="password != null and password != ''">
                password = #{password},
            </if>
            <if test="name != null and name != ''">
                name = #{name},
            </if>
            <if test="gender != null">
                gender = #{gender},
            </if>
            <if test="image != null and image != ''">
                image = #{image},
            </if>
            <if test="job != null">
                job = #{job},
            </if>
            <if test="ed != null">
                entrydate = #{ed},
            </if>
            <if test="deptId != null">
                dept_id = #{deptId},
            </if>
            <if test="createTime != null">
                create_time = #{createTime},
            </if>
            <if test="updateTime != null">
                update_time = #{updateTime},
            </if>
        </set>
        where id = #{id}
    </update>

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


</mapper>

5.6XML配置实现

代码如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--在控制台输出发送的sql日志-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>


    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>

            <!--目前只关注这部分内容,它的作用就是声明要连接的数据信息-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--声明含有sql的接口所在包-->
        <package name="com.itheima.mapper"/>
    </mappers>
</configuration>

5.7测试实现

代码如下:

package com.itheima.test;

import com.itheima.domain.Emp;
import com.itheima.mapper.EmpMapper;
import com.itheima.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

public class EmpMapperTest {

    // 测试查询所有
    @Test
    public void testFindAll(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试结果集映射开启驼峰命名规则
    @Test
    public void testFindAll1(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll1();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试结果集映射起别名
    @Test
    public void testFindAll2(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll2();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试结果集映射手动结果映射@Results @Result
    @Test
    public void testFindAll3(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findAll3();
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试条件查询
    @Test
    public void testFindCondition(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findByCondition("张三丰",1, LocalDate.of(2000,1,1),LocalDate.of(2020,1,1));
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试模糊查询
    @Test
    public void testFindCondition2(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        List<Emp> empList = empMapper.findByCondition2("张",1, LocalDate.of(2000,1,1),LocalDate.of(2020,1,1));
        for (Emp emp : empList) {
            System.out.println(emp);
        }
        MybatisUtil.close(sqlSession);
    }
    // 测试根据id查询
    @Test
    public void testFindById(){

        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);
        Emp emp1 = empMapper.findById(4);
        System.out.println(emp1);
        MybatisUtil.close(sqlSession);
    }

    //条件查询
    @Test
    public void testFindByCondition() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        //List<Emp> empList = empMapper.findByCondition3("张", (short) 1, LocalDate.of(2002, 01, 01), LocalDate.of(2023, 12, 31));
        //List<Emp> empList = empMapper.findByCondition3("张", (short) 1, null, null);
        List<Emp> empList = empMapper.findByCondition3("", (short) 1, null, null);
        empList.forEach(e -> System.out.println(e));//lambda方式打印

        MybatisUtil.close(sqlSession);
    }

    //更新
    @Test
    public void testUpdate() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        Emp emp = new Emp();
        emp.setId(2);
        emp.setUsername("haha2");
        emp.setName("sdnajn");
        emp.setGender( (short) 1);
        emp.setImage("haha.jpg");
        emp.setJob((short) 2);
        emp.setDeptId(1);
        emp.setCreateTime(LocalDateTime.of(2023, 1, 1, 1, 1,1));
        emp.setUpdateTime(LocalDateTime.now());

        empMapper.update(emp);

        MybatisUtil.close(sqlSession);
    }

    //批量删除
    @Test
    public void deleteByIds() {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        empMapper.deleteByIds(Arrays.asList(13, 14, 15));

        MybatisUtil.close(sqlSession);
    }

}

5.8pom.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.itheima</groupId>
    <artifactId>day04-01-mybatis</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>

    <dependencies>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.9</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
        </dependency>
    </dependencies>

</project>

总结

以上就是今天学习的内容。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1924941.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Ubuntu 安装搜狗输入法

搜狗输入法已支持Ubuntu1604、1804、1910、2004、2010 各系统安装步骤可能略有不同 1、添加中文语言支持 打开 系统设置——区域和语言——管理已安装的语言——在“语言”tab下——点击“添加或删除语言” 弹出“已安装语言”窗口&#xff0c;勾选中文&#xff08;简体&…

【 香橙派 AIpro评测】烧系统到运行并使用Jupyter Lab 界面体验 AI 应用样例(新手福音)

文章目录 ⭐前言⭐初始化开发板⭐下载镜像烧系统⭐开发板初始化系统&#x1f496; 远程ssh&#x1f496;查看ubuntu桌面&#x1f496; 远程向日葵 ⭐体验 AI 应用样例&#x1f496; 运行 jupyterLab&#x1f496; 打开Jupyter Lab页面&#x1f496; 释放内存&#x1f496; 运行…

C#语句与方法

文章目录 语句判断语句循环语句循环控制语句 C#方法&#xff08;函数&#xff09;C#方法定义参数传递 语句 判断语句 语句描述if语句if(判定条件){}&#xff0c;如果条件为真则执行对应代码&#xff0c;反之则跳过if...else语句if(判定条件){}else{}&#xff0c;判定条件为真…

【数据结构】手写堆 HEAP

heap【堆】掌握 手写上浮、下沉、建堆函数 对一组数进行堆排序 直接使用接口函数heapq 什么是堆&#xff1f;&#xff1f;&#xff1f;堆是一个二叉树。也就是有两个叉。下面是一个大根堆&#xff1a; 大根堆的每一个根节点比他的子节点都大 有大根堆就有小根堆&#xff1…

Mac和VirtualBox Ubuntu共享文件夹

1、VirtualBox中点击设置->共享文件夹 2、设置共享文件夹路径和名称&#xff08;重点来了&#xff1a;共享文件夹名称&#xff09; 3、保存设置后重启虚拟机&#xff0c;执行下面的命令 sudo mkdir /mnt/share sudo mount -t vboxsf share /mnt/share/ 注&#xff1a;shar…

Java 面试相关问题(上)——基础问题集合问题

这里只会写Java相关的问题&#xff0c;包括Java基础问题、JVM问题、线程问题等。全文所使用图片&#xff0c;部分是自己画的&#xff0c;部分是自己百度的。如果发现雷同图片&#xff0c;联系作者&#xff0c;侵权立删。 1. Java基础面试问题1.1 基本概念相关问题1.1.1 Java语言…

DHCPv6 详情及其报文介绍 - 附配置案例及验证命令(Cisco)

DHCPv6 诞生的原因 IPv6 协议具有地址空间巨大的特点&#xff0c;但同时长达 128 比特的 IPv6 地址又要求高效合理的地址自动分配和管理策略。IPv6 无状态地址配置方式&#xff08;RFC2462&#xff09;是目前广泛采用的 IPv6 地址自动配置方式。配置了该协议的主机只需相邻设备…

易懂的吉文斯(Givens)变换(一)

文章目录 二阶Givens旋转矩阵作用于向量作用于矩阵更一般的情况 二阶Givens旋转矩阵 在QR分解中&#xff0c;Givens旋转是一种用于将矩阵变成上三角形的技术。 别的教程里面往往会直接给出一个n*n阶的通用Givens矩阵形式&#xff0c;但是这样太过抽象难懂了&#xff0c;而且难…

特惠电影票api安全性如何评测

评测特惠电影票API的安全性是确保用户数据安全和系统稳定运行的关键步骤。以下是评测特惠电影票API安全性的一些方法和步骤&#xff1a; ### 1. **认证和授权** - **JWT认证**&#xff1a;使用JSON Web Token (JWT) 进行用户身份验证和授权&#xff0c;确保只有合法用户可以访…

旷野之间15 – Groq 和 AI 硬件

文讨论了 Groq,一种新的计算机硬件方法,它彻底改变了 AI 解决现实世界问题的方式。 在讨论 Groq 之前,我们将分析 AI 的根本含义,并探讨用于运行 AI 模型的计算机硬件的一些关键组件。即 CPU、GPU 和 TPU。我们将从 1975 年的 Z80 CPU 开始探索这些关键硬件,然后通过探索…

ubuntu服务器安装labelimg报错记录

文章目录 报错提示查看报错原因安装报错 报错提示 按照步骤安装完labelimg后&#xff0c;在终端输入labelImg后&#xff0c;报错&#xff1a; (labelimg) rootinteractive59753:~# labelImg ………………Got keys from plugin meta data ("xcb") QFactoryLoader::Q…

游戏三倍补帧工具 Lossless Scaling v2.9.0

运行时请将游戏窗口化或全屏 比如你的显示器是144hz 把游戏限制帧率到48帧后开启三倍补帧 允许撕裂和垂直同步一起来延迟更低 72,48,36&#xff0c;分别对应1/2&#xff0c;1/3&#xff0c;1/4&#xff0c;性能够的话&#xff08;补帧后满144fps&#xff09;就优先锁72fps&a…

【C++】 List 基本使用

C List 基本使用 基本概念 list 是一个序列容器&#xff0c;它内部维护了一个双向链表结构。与 vector 或 deque 等基于数组的容器不同&#xff0c;list 在插入和删除元素时不需要移动大量数据&#xff0c;因此在这些操作上具有较高的效率。然而&#xff0c;访问列表中的特定…

公共资源管理服务中心智能化方案PPT(97页)

公共资源管理服务中心智能化方案摘要 1. 建设背景及需求 公共资源管理服务中心的建设以便民、高效、廉洁、规范为宗旨&#xff0c;推行“一站式办公、一条龙服务、并联式审批、阳光下作业、规范化管理”的运行模式。目标是提高行政效率和社会效益&#xff0c;预防流程漏洞&am…

硬盘HDD:AI时代的战略金矿?

在这个AI如火如荼的时代&#xff0c;你可能以为硬盘HDD已经像那些过时的诺基亚手机一样&#xff0c;被闪存和云存储淘汰到历史的尘埃里。但&#xff0c;别急着给HDD们举行退休派对&#xff0c;因为根据Finis Conner这位硬盘界的传奇人物的说法&#xff0c;它们非但没退场&#…

旋转电连接器抗干扰性有哪几个方面?

旋转电连接器作为一种精密的电气传输装置&#xff0c;它实现了两个相对旋转部件间的功率和信号传输。通过旋转电连接器可以传输高频的交流电、高电压的交流电、大电流的交流电、弱小的直流小信号等多种电信号&#xff0c;但是由仪器之间的距离有限&#xff0c;在如此短的距离内…

C 语言结构体

本博客涉及的结构体知识有&#xff1a; 1.0&#xff1a;结构体的创建和使用 2.0: typedef 关键字与#define 关键字的区别 3.0: 结构体成员的访问【地址访问与成员访问】 4.0: 结构体嵌套调用 5.0 数组访问赋值结构体成员 ...... 1.0&#xff1a;结构体的创建和使用 结…

33.异步FIFO IP核的配置、调用与仿真

&#xff08;1&#xff09;异步FIFO的配置过程&#xff1a; ps&#xff1a;异步fifo相比较同步fifo少一个实际深度 &#xff08;2&#xff09;异步FIFO的调用: module dcfifo (input wr_clk ,input rd_clk ,input [7:0] …

LT_0001_两数之和

一、题目描述 二、代码实现 2.1 暴力枚举 时间复杂度O(N^2) public static int[] towSum(int[] nums, int target) {for (int i 0; i < nums.length; i) {for (int j i 1; j < nums.length; j) {if (nums[i] nums[j] target) {return new int[]{i,j};}}}return n…

github actions方式拉取docker镜像

参考&#xff1a; https://wkdaily.cpolar.cn/archives/gc 注意github actions提供的免费虚拟机空间有限&#xff0c;空间不足会报错&#xff0c;查看大概语句有10来G 我在workflow file里加了df -h 运行查看磁盘情况&#xff1a; 通过pwd命令&#xff0c;可以知道运行目录/ho…