JavaWeb开发-09-MyBatis

news2024/10/5 17:27:37

 官网:icon-default.png?t=N7T8https://mybatis.org/mybatis-3/zh/index.html

一.Mybatis入门

1.快速入门

 


2.JDBC介绍


3.数据库连接池

 官方地址:icon-default.png?t=N7T8https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter


4.lombok

二.Mybatis基础增删改查

1.准备


2.删除

 


3.新增

 


4.更新


5.查询

# 配置数据库的连接信息 - 四要素

#驱动类名称
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

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

#开启mybatis的驼峰命名自动映射开关
mybatis.configuration.map-underscore-to-camel-case=true
package com.wjh.pojo;

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 entrydate;
    private Integer deptId;
    private LocalDateTime createTime;
    private LocalDateTime updateTime;

}
package com.wjh.mapper;

import com.wjh.pojo.Emp;
import org.apache.ibatis.annotations.*;

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

@Mapper
public interface EmpMapper {

    //查询所有员工信息
    @Select("select * from emp")
    public List<Emp> select();

    //根据ID删除员工信息操作
    @Delete("delete from emp where id = #{id}")
    //public void delete(Integer id);
    public int delete(Integer 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);

    //更新员工信息(修改)
    @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查询用户信息
    @Select("select * from emp where id = #{id}")
    public Emp selectId(Integer id);

//    //方案一给字段起别名,让别名与实体名一致
//    @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 selectId2(Integer id);
//
//    //方案二: 通过#@Result注解手动映射
//    @Results({
//            @Result(column = "dept_id",property =  "deptId"),
//            @Result(column = "create_time",property =  "createTome"),
//            @Result(column = "update_time",property =  "updateTime")
//    })
//    @Select("select * from emp where id = #{id}")
//    public Emp selectId3(Integer id);

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

    //条件查询员工信息
    @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 );

//    select concat('hello', 'mysql', 'word');
//     select * from emp where name like concat('%', '张', '%') and gender = '1' and
//     entrydate between '2010-01-01' and '2020-01-01' order by update_time desc;

}

package com.wjh;

import com.wjh.mapper.EmpMapper;
import com.wjh.pojo.Emp;
import org.apache.ibatis.annotations.Mapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest
class SpringbootMybatisCrudApplicationTests {

    @Autowired
    private EmpMapper EmpMapper;

    //查询所有员工测试类
    @Test
    public void testListEmp(){
        List<Emp> empList = EmpMapper.select();
        empList.stream().forEach(selectEmp -> {
            System.out.println(selectEmp);
        });
    }

    //根据id删除员工信息测试类
    @Test
    public void testDelete(){
        EmpMapper.delete(4);
        //int delete = EmpMapper.delete(4);
        //System.out.println("删除了" + delete + "条数据");
        testListEmp();
    }

    //新增员工测试类

    @Test
    public void testInsert(){
        Emp empInsert = new Emp();
        empInsert.setUsername("ikun6");
        empInsert.setName("坤坤6");
        empInsert.setGender((short)2);
        empInsert.setImage("#");
        empInsert.setJob((short)1);
        empInsert.setEntrydate(LocalDate.of(2000,01,01));
        empInsert.setDeptId(1);
        empInsert.setCreateTime(LocalDateTime.now());
        empInsert.setUpdateTime(LocalDateTime.now());
        //执行员工信息操作
        EmpMapper.insert(empInsert);
        System.out.println("主键:" + empInsert.getId());
    }

    //修改员工信息测试类
    @Test
    public void testUpdate(){
        Emp empUpdate = new Emp();
        empUpdate.setId(10);
        empUpdate.setUsername("zhaomingming");
        empUpdate.setName("赵敏");
        empUpdate.setGender((short)1);
        empUpdate.setImage("#");
        empUpdate.setJob((short)1);
        empUpdate.setEntrydate(LocalDate.of(2000,01,01));
        empUpdate.setDeptId(1);
        empUpdate.setUpdateTime(LocalDateTime.now());

        //执行员工信息操作
        EmpMapper.update(empUpdate);
    }

    //根据id查询用户信息测试类
    @Test
    public void testSelectId(){
        Emp emp = EmpMapper.selectId(10);
        System.out.println(emp);
    }

    //根据条件查询员工
    @Test
    public void testSelect(){
        EmpMapper.list("张", (short) 1, LocalDate.of(2010, 01, 01), LocalDate.of(2020, 01 , 01));
    }

}

 三.Mybatis动态SQL

1.XML映射文件

 

 

 

 //条件查询员工信息
    public List<Emp> list(String name, Short gender, LocalDate begin, LocalDate end);
<?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.wjh.mapper.EmpMapper">
<!--   resultType:单条记录所封装的类型 -->
    <select id="list" resultType="com.wjh.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>
//根据条件查询员工
    @Test
    public void testSelect(){
        List<Emp> empList = EmpMapper.list("张", (short) 1,
                LocalDate.of(2010, 01, 01),
                LocalDate.of(2020, 01 , 01));
        System.out.println(empList);
    }

 

 

 

官方说明icon-default.png?t=N7T8https://mybatis.net.cn/getting-started.html

 

2.动态SQL

(1).<if>

 

 

<select id="list" resultType="com.wjh.pojo.Emp">
<!--         resultType:单条记录所封装的类型-->
<!--         select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time-->
<!--         from emp-->
<!--         where-->
<!--               <if test="name != null">-->
<!--                  name like concat('%', #{name}, '%')-->
<!--               </if>-->
<!--         and gender = #{gender}-->
<!--         and entrydate between #{begin} and #{end}-->
<!--         order by update_time desc-->


<!--    ===============================动态SQL=======================-->
        <!-- if -->
        select *
        from emp
        <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>

 

//动态更新员工信息(修改)
    //@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 update2(Emp emp);

 

<!--   动态更新员工信息(修改) -->
    <update id="update2">
        update emp
        <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>

 

 //动态更新员工信息-- 跟新id = 18 的员工 username 为 Tom11,name = 汤姆111, gander更新为2

    @Test
    public void testUpdate2(){
        //构造员工对象
        Emp emp = new Emp();
        emp.setId(19);
        emp.setUsername("tanmgu11");
        emp.setName("汤姆111");
        emp.setGender((short) 2);
        emp.setUpdateTime(LocalDateTime.now());
        //执行员工操作
        EmpMapper.update2(emp);

    }


(2).<foreach>

 

//批量删除员工
    public void deleteByIds(List<Integer> ids);
<!--批量删除员工信息 (22,23,24)-->
<!--
    collection:     遍历的集合
    item:           遍历出来的元素
    separator:      分隔符
    open:           遍历开始前的SQl片段
    close:          遍历结束后的SQL片段
-->
    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>
//批量删除员工
    @Test
    public void testdeleteByIds(){
        List<Integer> list = Arrays.asList(16,17,18);
        EmpMapper.deleteByIds(list);
    }

(3).<sql><include>

 

 

<?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.wjh.mapper.EmpMapper">
    
    <sql id="commonSelect">
        select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time
        from emp
    </sql>

    <select id="list" resultType="com.wjh.pojo.Emp">
<!--         resultType:单条记录所封装的类型-->
<!--         select id, username, password, name, gender, image, job, entrydate, dept_id, create_time, update_time-->
<!--         from emp-->
<!--         where-->
<!--               <if test="name != null">-->
<!--                  name like concat('%', #{name}, '%')-->
<!--               </if>-->
<!--         and gender = #{gender}-->
<!--         and entrydate between #{begin} and #{end}-->
<!--         order by update_time desc-->


<!--    ===============================动态SQL=======================-->
        -- if
        <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>


<!--   动态更新员工信息(修改) -->
    <update id="update2">
        update emp
        <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>

<!--批量删除员工信息 (22,23,24)-->
<!--
    collection:     遍历的集合
    item:           遍历出来的元素
    separator:      分隔符
    open:           遍历开始前的SQl片段
    close:          遍历结束后的SQL片段
-->
    <delete id="deleteByIds">
        delete from emp where id in
        <foreach collection="ids" item="id" separator="," open="(" close=")">
            #{id}
        </foreach>
    </delete>



</mapper>

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

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

相关文章

AT24C02芯片

AT24C02简介&#xff1a; AT24C01/02/04/08/16...是一个 1K/2K/4K/8K/16K 位串行 CMOS内部有9个字节&#xff1b; 该器件通过 I2C 总线接口进行 操作&#xff0c;它有一个专门的写保护功能&#xff1b; 基于51 他有这个芯片操作 时序&#xff1a; AT24C02软件编程&#xff1a; …

darknet yolov3 模型训练步骤整理

1. 把需要训练的图片拷贝到 D:\模型训练\darknet-master\build\darknet\x64\data\VOCdevkit\VOC2012\JPEGImage 2. 执行imageName.py 文件&#xff0c;重命名JPEGImage下的图片。 D:\模型训练\darknet-master\build\darknet\x64\data\VOCdevkit\VOC2012\imageName.py 3. 用…

Termius 8 for Mac(多协议服务器连接软件)

Termius是一款远程访问和管理工具&#xff0c;旨在帮助用户轻松地远程连接到各种服务器和设备。它适用于多种操作系统&#xff0c;包括Windows、macOS、Linux和移动设备。 该软件提供了一个直观的界面&#xff0c;使用户可以通过SSH、Telnet和Mosh等协议连接到远程设备。它还支…

微表情识别API + c++并发服务器系统

微表情识别API系统 该项目只开源前后端程序&#xff0c;模型不开源 地址&#xff1a;https://github.com/lin-lai/-API- 更新功能 4.1版本 改用epoll实现IO多路复用并发服务器去除标志位设定—正在考虑用协议实现 项目介绍 本项目用于检测并识别视频中人脸的微表情 目标任…

【插件】页面引导库driver.js:

文章目录 一、效果图:二、实现思路:三、实现代码:【1】Driver.js 的技术特性【2】安装依赖【3】代码实现【4】 配置相关参数 一、效果图: 二、实现思路: 【官网】https://driverjs.com/docs/installation 【npm】https://www.npmjs.com/package/driver.js 【案例】改造driver.j…

用Python在XML和Excel表格之间实现互转

XML是一种超文本标记语言和文件格式&#xff0c;具有可自定义标签&#xff0c;易于扩展&#xff0c;便于编辑&#xff0c;传输便捷等优点。XML已成为应用数据交换的常用方式。虽然XML格式易于传输和开发者操作&#xff0c;但对于普通用户来说&#xff0c;数据以xls或xlsx的形式…

二维穿墙雷达CW112 的 优势

TFN CW112加固型二维定位穿墙雷达是一款综合UWB雷达和生物医学工程技术研制而成的人体目标探测装备。该产品可穿透建筑墙体等障碍物&#xff0c;实时获取其后方人体目标位置及数量等信息&#xff0c;具有穿透性强、轻质便携、可双手操控等特点&#xff0c;广泛应用于反恐处突、…

vue+element项目创建步骤

一、创建vue项目步骤 要创建一个Vue Element UI的项目&#xff0c;你可以按照以下步骤进行操作&#xff1a; 1.确保你已经安装了Node.js和npm&#xff08;Node.js的包管理器&#xff09;。你可以在命令行中运行以下命令来检查它们是否已经安装&#xff1a; node -vnpm -v2.使…

视频超过1g怎么压缩?分享简单的视频压缩方法

随着科技的发展&#xff0c;视频已经成为了我们日常生活中不可或缺的一部分。然而&#xff0c;有时候我们会遇到视频文件过大&#xff0c;无法顺利传输或存储的问题。那么&#xff0c;如何解决视频超过1g压缩的问题呢&#xff1f; #长假读书清单# 首先我们可以借助专业的压缩…

华为云云耀云服务器L实例评测|运行python脚本

目录 一、往期回顾二、华为云云耀云服务器L实例使用流程1、账号注册2、购买并配置云耀云服务器L实例3、登录并使用云耀云服务器L实例 三、为什么Python越来越火&#xff1f;四、使用宝塔运行Python脚本1、下载Python项目管理器2、上传项目到服务器3、添加项目4、安装requests启…

一文读懂Llama 2(从原理到实战)

简介 Llama 2&#xff0c;是Meta AI正式发布的最新一代开源大模型。 Llama 2训练所用的token翻了一倍至2万亿&#xff0c;同时对于使用大模型最重要的上下文长度限制&#xff0c;Llama 2也翻了一倍。Llama 2包含了70亿、130亿和700亿参数的模型。Meta宣布将与微软Azure进行合…

便携式水质采样设备助力毒情监测

便携式水质采样设备助力毒情监测 污水涉毒采样检测工作是运用科技手段准确评估监测辖区内毒情形势的重要手段。期间&#xff0c;民警详细了解了生活和工业污水的处理、排放以及服务范围、人口数量等情况&#xff0c;并就污水涉毒采样检测工作达成共识。随后&#xff0c;民警严格…

【车载开发系列】ECU Application Software程序刷新步骤

【车载开发系列】ECU Application Software程序刷新步骤 ECU Application Software程序刷新步骤 【车载开发系列】ECU Application Software程序刷新步骤一. Boot Software&#xff08;引导软件&#xff09;1&#xff09;boot manager&#xff08;启动管理器&#xff09;2&…

Flink1.12.7 Standalone版本安装

官网下载版本&#xff1a;https://archive.apache.org/dist/flink/flink-1.12.7/flink-1.12.7-bin-scala_2.12.tgz 可以从首页找到Downloads | Apache Flink&#xff0c;一直往下拉 安装&#xff1a;下载后直接解压即可 添加全局参数&#xff1a; #vi /etc/profile FLINK_HO…

云服务器免费体检

三丰云提供了免费云服务器与免费虚拟主机服务&#xff0c; 个人学习、搭建个人网站或者微信小程序调试等可以申请一台。 免费申请网址为&#xff1a; https://www.sanfengyun.com/ 还是挺方便的&#xff0c;大家可以体验体验。

【校招VIP】前端操作系统之I/O调度算法

考点介绍 I/O 调度算法在各个进程竞争磁盘I/O的时候担当了裁判的角色。他要求请求的次序和时机做最优化的处理&#xff0c;以求得尽可能最好的整体I/O性能。 前端操作系统之I/O调度算法-相关题目及解析内容可点击文章末尾链接查看&#xff01; 一、考点题目 1. 某文件占10个…

Kafka的消息存储机制

前面咱们简单讲了K啊开发入门相关的概念、架构、特点以及安装启动。 今天咱们来说一下它的消息存储机制。 前言&#xff1a; Kafka通过将消息持久化到磁盘上的日志文件来实现高吞吐量的消息传递。 这种存储机制使得Kafka能够处理大量的消息&#xff0c;并保证消息的可靠性。 1…

西门子S7-1200使用LRCF通信库与安川机器人进行EthernetIP通信的具体方法示例

西门子S7-1200使用LRCF通信库与安川机器人进行EthernetIP通信的具体方法示例 准备条件: PLC:S7-1200 1214C DC/DC/DC 系统版本4.5及以上。 机器人控制柜:安川YRC1000。 软件:TIA V17 PLC做主站,机器人做从站。 具体方法可参考以下内容: 使用的库文件为西门子 1200系列…

[React] react-hooks如何使用

react-hooks思想和初衷&#xff0c;也是把组件&#xff0c;颗粒化&#xff0c;单元化&#xff0c;形成独立的渲染环境&#xff0c;减少渲染次数&#xff0c;优化性能。 文章目录 1.为什么要使用hooks2.如何使用hooks2.1 useState2.2 useEffect2.3 useLayoutEffect2.4 useRef2.5…