【教学典型案例】28.单表的11个Update接口--MyBatis

news2025/7/20 17:29:57

目录

  • 一:背景介绍
  • 二:前期准备
    • 引入pom依赖
    • MyBatis配置文件
    • 数据库连接文件
    • MyBatis配置类
  • 三:代码编写
    • Mapper编写
      • 接口
      • 通用mapper
      • 实体pojo
      • junit测试编写
    • 测试结果
  • 四:总结

一:背景介绍

在进行项目开发编写更新接口时,编写了11个Update接口,这样可以实现最后的功能效果,但是后期如果需要维护的话是十分难得。也无法进行复用和扩展。
在这里插入图片描述
下边的例子中,给大家展示了如何编写可复用、可扩展、维护成本低的SQL语句。

二:前期准备

代码环境:Java MyBatis maven项目,Mysql

引入pom依赖

需要引入mysql、mybatis、junit三个依赖即可。

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

MyBatis配置文件

实体类包的路径和接口mapper的路径需要改成自己的路径
在这里插入图片描述

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration mybatis的核心配置文件-->
<configuration>
<!--引入外部配置文件-->
    <properties resource="db.properties"/>
    
    <!--配置-->
    <settings>
        <!--标准日志工厂设置-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
<!--显示的开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
<!--可以给实体类取别名-->
    <typeAliases>
      <!--<typeAlias type="com.wangsiqi.pojo.User" alias="User"/>-->
        <!--可以指定一个包名,MyBatis会在包名下面搜索需要的Java Bean-->
        <package name="com.wangsiqi.pojo"/>
    </typeAliases>

    <!--environments 后面的s表示这是一个复数,可以编写多套环境  default表示默认的环境为development-->
    <environments default="development">
        <!--编写一套环境 名称为configuration-->
        <environment id="development">
            <!--jdbc的事务管理-->
            <transactionManager type="JDBC"/>
            <!--配置数据库相关数据-->
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <!--userSSL是一个按权连接 &amp是一个转移符 等同于and  CharacterEncoding=utf-8可以保证输入数据库的数据不乱码-->
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

<!--绑定接口-->
    <mappers>
        <mapper class="com.wangsiqi.dao.UserCourseGroupConfigurationMapper"/>
    </mappers>
</configuration>

数据库连接文件

先进行数据库的连接
在这里插入图片描述
在这里插入图片描述

MyBatis配置类

//sqlSessionFactory(获取资源) 必然是构建 sqlSession
//该工具类的作用时读取配置文件 获取sqlSessionFactory工厂
public class MybatisUtils {
    private  static  SqlSessionFactory sqlSessionFactory; //该代码的作用是提升作用域 可以让getSqlSession方法使用sqlSessionFactory
    static{ //静态代码块:一旦初始化就加载

        try {
            //使用Mybatis第一步:获取sqlSessionFactory对象
            String resource = "mybatis-config.xml"; //获取资源,直接读到mybatis-config.xml
            InputStream inputStream = Resources.getResourceAsStream(resource); //需要用到输入流(InputStream) 把resource类加载进来
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//通过build把输入流加载进来
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句

    public static SqlSession getSqlSession() { //该方法会返回一个SqlSession类
//        SqlSession sqlSession = sqlSessionFactory.openSession();
//        return sqlSession;
        return sqlSessionFactory.openSession(true);//openSession中有自动commit(提交)事务的方法,加上true就能实现

    }

}

以上就是我们所需的基本环境啦,接下来就可以进行代码的编写啦~!

三:代码编写

Mapper编写

接口

public interface UserCourseGroupConfigurationMapper {
    void updateCourseGroupConfiguration(@Param("reviseParam")UserCourseGroupConfigurationPojo reviseParam, @Param("conditionParam")UserCourseGroupConfigurationPojo conditionParam);
}

通用mapper

    <update id="updateCourseGroupConfiguration">
        update arpro_user_course_group_configuration
        <trim prefix="SET" suffixOverrides=",">
            <if test="reviseParam.infoId != null">info_id = #{reviseParam.infoId}</if>
            <if test="reviseParam.courseId != null">course_id = #{reviseParam.courseId}</if>
            <if test="reviseParam.classId != null">class_id = #{reviseParam.classId}</if>
            <if test="reviseParam.groupId != null">group_id = #{reviseParam.groupId}</if>
            <if test="reviseParam.type != null">type = #{reviseParam.type}</if>
            <if test="reviseParam.isDelete != null">is_delete = #{reviseParam.isDelete}</if>
            <if test="reviseParam.remark != null">remark = #{reviseParam.remark}</if>
            <if test="reviseParam.isMostLike != null">is_like = #{reviseParam.isLike}</if>
        </trim>
        where is_delete = 0
        <if test="conditionParam.infoId != null"> and info_id = #{conditionParam.infoId}</if>
        <if test="conditionParam.courseId != null">and course_id = #{conditionParam.courseId}</if>
        <if test="conditionParam.classId != null">and class_id = #{conditionParam.classId}</if>
        <if test="conditionParam.groupId != null">and group_id = #{conditionParam.groupId}</if>
        <if test="conditionParam.isMostLike != null">and is_like = #{conditionParam.isLike}</if>
        <if test="conditionParam.type != null">and type = #{conditionParam.type}</if>
    </update>

实体pojo

@Data
public class UserCourseGroupConfigurationPojo {
    /**
     * 主键id
     */
    private BigInteger id;

    /**
     * 信息id是用户表的关联键
     */
    private BigInteger infoId;

    /**
     * 课程id
     */
    private BigInteger courseId;

    /**
     * 班级id
     */
    private BigInteger classId;

    /**
     * 分组id
     */
    private BigInteger groupId;

    /**
     * 我学的课还是我教的课
     */
    private Integer  type;

    /**
     * 是否删除 0 否 1是
     */
    private Integer isDelete;

    /**
     * 创建时间
     */
    private Date createTime;

    /**
     * 更新时间
     */
    private Date updateTime;

    /**
     * 备注
     */
    private String remark;

    /**
     * 分组名称
     */
    private String groupName;

    /**
     * 分组顺序
     */
    private Integer sequence;

    /**
     * 是否是默认分组
     */
    private Integer isDefault;

    /**
     * 是否为我喜欢分组 0其他分组,1特别关注分组
     */
    private Integer isMostLike;

    public BigInteger getId() {
        return id;
    }

    public void setId(BigInteger id) {
        this.id = id;
    }

    public BigInteger getInfoId() {
        return infoId;
    }

    public void setInfoId(BigInteger infoId) {
        this.infoId = infoId;
    }

    public BigInteger getCourseId() {
        return courseId;
    }

    public void setCourseId(BigInteger courseId) {
        this.courseId = courseId;
    }

    public BigInteger getClassId() {
        return classId;
    }

    public void setClassId(BigInteger classId) {
        this.classId = classId;
    }

    public BigInteger getGroupId() {
        return groupId;
    }

    public void setGroupId(BigInteger groupId) {
        this.groupId = groupId;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }


    public Integer getIsDelete() {
        return isDelete;
    }

    public void setIsDelete(Integer isDelete) {
        this.isDelete = isDelete;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public String getGroupName() {
        return groupName;
    }

    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    public Integer getSequence() {
        return sequence;
    }

    public void setSequence(Integer sequence) {
        this.sequence = sequence;
    }

    public Integer getIsDefault() {
        return isDefault;
    }

    public void setIsDefault(Integer isDefault) {
        this.isDefault = isDefault;
    }

    public Integer getIsMostLike() {
        return isMostLike;
    }

    public void setIsMostLike(Integer isMostLike) {
        this.isMostLike = isMostLike;
    }
}

junit测试编写

public class UserCourseGroupConfigurationTest {
    @Test
    public void test(){
        //获取数据库连接
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserCourseGroupConfigurationMapper userCourseGroupConfigurationMapper = sqlSession.getMapper(UserCourseGroupConfigurationMapper.class);

        //进行更新操作
        UserCourseGroupConfigurationPojo reviseParam = new UserCourseGroupConfigurationPojo();
        UserCourseGroupConfigurationPojo conditionParam = new UserCourseGroupConfigurationPojo();
        //假删除某个课的某个班的所有信息
        /*reviseParam.setIsDelete(0);
        conditionParam.setCourseId(BigInteger.valueOf(223667994));
        conditionParam.setClassId(BigInteger.valueOf(56496292));*/
        //reviseParam是修改后的数据
        reviseParam.setCourseId(new BigInteger("315282991842590721"));
        //conditionParam是修改条件
        conditionParam.setCourseId(new BigInteger("315282991842590720"));
        conditionParam.setType(1);
        //进行调用
        userCourseGroupConfigurationMapper.updateCourseGroupConfiguration(reviseParam,conditionParam);
    }
}

测试结果

没执行代码之前的数据库表数据
在这里插入图片描述
在这里插入图片描述
执行成功后,数据库中type=1的数据不见了
在这里插入图片描述
然后使用course_id=315282991842590721修改后的数据进行查询
在这里插入图片描述

四:总结

通过以上分析,更加认识到了面向对象的思想是多么的伟大。我们一直都说做软件设计要使用面向对象的思想:可复用、可扩展、可维护,可是真的做起来没有做到知行合一。

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

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

相关文章

顶级动漫IP加持之下,3A策略游戏Mechaverse如何改变GameFi

2021年是元宇宙发展的元年&#xff0c;元宇宙与GameFi创造了一波又一波市场热点。在经历第一波热潮之后&#xff0c;元宇宙的到来让不少人看到了加密市场的潜力&#xff0c;同时大家也意识到这将是未来的重要方向。如何将元宇宙推向更广阔的市场&#xff0c;让更多人能够轻松进…

项目管理工具DHTMLX Gantt灯箱元素配置教程:显示任务内容

DHTMLX Gantt是用于跨浏览器和跨平台应用程序的功能齐全的Gantt图表。可满足项目管理应用程序的大部分开发需求&#xff0c;具备完善的甘特图图表库&#xff0c;功能强大&#xff0c;价格便宜&#xff0c;提供丰富而灵活的JavaScript API接口&#xff0c;与各种服务器端技术&am…

神经网络(容易被忽视的基础知识)

主要内容&#xff1a; 基本神经元作为线性分类器的单个神经元为什么要是深度神经网而不是”肥胖“神经网络&#xff1f;为什么在人工神经网络中的神经元需要激活函数&#xff1f;一些主要的激活函数神经网络中的偏置有什么意义&#xff1f;初始化神经网络的参数可以全为0吗&am…

【java】java基本类型和包装类型的区别

文章目录简介1.包装类型可以为 null&#xff0c;而基本类型不可以2.包装类型可用于泛型&#xff0c;而基本类型不可以3.基本类型比包装类型更高效4.自动装箱和自动拆箱简介 Java 的每个基本类型都对应了一个包装类型&#xff0c;比如说 int 的包装类型为 Integer&#xff0c;d…

ECOLOY直接更换流程表单后导致历史流程中数据为空白的解决方案

用户反馈流历史流程打开是空白了没有内容。 一、问题调查分析&#xff1a; 工作流“XX0204 员工培训协议审批流程”workflowId37166产生的7个具体流程中&#xff0c;创建日期为2021年的4个具体流程原先引用的数据库表单应该是“劳动合同签订审批表”(formtable_main_190)&…

JavaScript-缓存

参考资料彻底解决让用户清一下浏览器缓存浏览器缓存彻底理解浏览器的缓存机制彻底弄懂前端缓存浅解强缓存和协商缓存浏览器缓存策略(强缓存和协商缓存)一文搞定Http缓存-强制缓存与协商缓存前端浏览器缓存知识梳理ASP.NET Core 中使用缓存IIS中设置Cache-Control是什么当我们第…

[Gin]框架底层实现理解(一)

前言&#xff1a;路由原理———压缩字典 这边简单讲一下gin非常重要的一个基点&#xff0c;也就是他作为go web框架的一个亮点 也就是Trie树和压缩字典算法 gin 通过树来存储路由&#xff0c;讲路由的字符拆解为一个个的结点&#xff0c;在获取handler函数时&#xff0c;会…

项目管理系统软件有哪些?这10款最好用的项目管理软件值得推荐

项目管理系统软件有哪些&#xff1f;这10款好用的项目管理系统软件值得推荐 如今企业规模不断扩大&#xff0c;业务逐渐复杂化&#xff0c;项目管理系统已经成为现代企业管理中不可或缺的一环&#xff1b; 而项目管理系统软件不仅可以保证项目按时完成&#xff0c;提高团队的…

【Java基础 下】 029 -- 多线程

目录 一、为什么要有多线程&#xff1f; 1、线程与进程 2、多线程的应用场景 3、小结 二、多线程中的两个概念&#xff08;并发和并行&#xff09; 1、并发 2、并行 3、小结 三、多线程的三种实现方式 1、继承Thread类的方式进行实现 2、实现Runnable接口的方式进行实现 3、利用…

MySQL简述

一、什么是数据库 数据库&#xff08;DB&#xff0c;DataBase&#xff09; 概念&#xff1a;数据仓库&#xff0c;相当于一款软件&#xff0c;安装在操作系统&#xff08;Windows&#xff0c;Linux&#xff0c;mac&#xff0c;…&#xff09;之上&#xff0c;可以存储大量的数…

nvm安装及使用(win)

一、安装nvm 下载地址&#xff1a;下载之后安装包安装 安装路径不要有中文或者空格 安装时尽量不要选择系统盘&#xff08;安装在系统盘可能会涉及到权限问题&#xff09; 安装前一定要把 node 的环境变量和 npm 的环境变量删除&#xff0c;否则在切换 node 版本时会报错 二、…

SCL_PFENET跑通填坑

1.数据准备&#xff1a;VOC2012数据集&#xff0c;initmodel文件夹&#xff08;预训练模型&#xff09;&#xff0c;SegmentationClassAug数据2.训练部分&#xff1a;训练部分没什么需要改动的&#xff0c;也就改一下选择的配置文件。在config文件夹里有关于coco和voc数据的配置…

备战蓝桥杯Day3python——迭代器的使用

python封装的迭代器 我们接下来介绍用于返回笛卡尔积的Permutations函数 Permutations(iterator, r) r:表示进行迭代后返回的长度 实例&#xff1a; >>> from itertools import permutations >>> a abc >>> for i in permutations(a,3):print …

Java深拷贝,浅拷贝

一、浅拷贝&#xff1a; &#xff08;1&#xff09; 对于数据类型是基本数据类型的成员变量&#xff0c;浅拷贝会直接进行值传递&#xff0c;也就是将该属性复制一份给新的对象。因为是两份不同的数据&#xff0c;所以对其中一的对象的成员变量值进行修改&#xff0c;不会影响另…

大考在即 百度版ChatGPT会翻车吗?

文心一言的发布会定档3月16日&#xff0c;不出意外&#xff0c;百度创始人李彦宏、CTO王海峰将出现在北京总部的发布会现场。这是百度版ChatGPT最新的官方消息&#xff0c;2月7日&#xff0c;文心一言首次官宣&#xff0c;当时称&#xff0c;产品“3月见”。 3月如期而至&…

C语言再学习 -- __attribute__详解

一、attribute 介绍 __attribute__是一个编译属性&#xff0c;用于向编译器描述特殊的标识、错误检查或高级优化。它是GNU C特色之一&#xff0c;系统中有许多地方使用到。__attribute__可以设置函数属性&#xff08;Function Attribute&#xff09;、变量属性&#xff08;Var…

JavaScript 如何优雅地获取多层级response中的某个深层次字段 ?. 可选链条(Optional chaining)

文章目录一句话场景&#xff1a;从一个多层级对象中拿一个处在深层次位置的字段MDN 可选链搜索引擎使用一句话 var marriedFlag response.data.userList[0].married; // 如果中间某个对象为空&#xff0c;会报Errorvar marriedFlag response?.data?.userList[0]?.married…

外贸新手找客户的开发信修炼之旅(一)

开发信是一种传统的开发海外客户的方式&#xff0c;相信即便是外贸新手也或多或少有所耳闻&#xff0c;甚至已经通过邮件开发到了一些有意向的客户&#xff0c;但有时也会遇到开发信效果不好的情况&#xff0c;收到的回复寥寥无几。其实说白了开发信的本质与派发传单相同&#…

李开复已经对美图公司失去耐心,并在美图公司身上损失惨重

来源&#xff1a;猛兽财经 作者&#xff1a;猛兽财经 猛兽财经经过对美图公司&#xff08;01357&#xff09;的投资人回报、产品、业务结构、战略、财务业绩、估值等方面进行了研究&#xff0c;认为美图这家公司不行&#xff0c;非常不看好&#xff0c;以下是理由供你参考。一…

10 Seata配置Nacos注册中心和配置中心

Seata配置Nacos注册中心和配置中心 Seata支持注册服务到Nacos&#xff0c;以及支持Seata所有配置放到Nacos配置中心&#xff0c;在Nacos中统一维护&#xff1b; 高可用(集群)模式下就需要配合Nacos来完成: 具体配置如下 注册中心 Seata-server端配置注册中心&#xff0c;…