【项目实战典型案例】27.单表的11个Update接口--MyBatis

本文涉及的产品
云数据库 RDS MySQL Serverless,0.5-2RCU 50GB
云数据库 RDS MySQL Serverless,价值2615元额度,1个月
简介: 【项目实战典型案例】27.单表的11个Update接口--MyBatis

一:背景介绍

在进行项目开发编写更新接口时,编写了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修改后的数据进行查询

四:总结

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


相关实践学习
基于CentOS快速搭建LAMP环境
本教程介绍如何搭建LAMP环境,其中LAMP分别代表Linux、Apache、MySQL和PHP。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
2月前
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
Mybatis+mysql动态分页查询数据案例——测试类HouseDaoMybatisImplTest)
22 1
|
2月前
Mybatis+mysql动态分页查询数据案例——房屋信息的实现类(HouseDaoMybatisImpl)
Mybatis+mysql动态分页查询数据案例——房屋信息的实现类(HouseDaoMybatisImpl)
24 2
|
2月前
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
Mybatis+mysql动态分页查询数据案例——工具类(MybatisUtil.java)
18 1
|
18天前
|
Java 数据库连接 数据库
MybatisPlus中IService接口有什么用?
MybatisPlus中IService接口有什么用?
|
18天前
|
Java 数据库连接 mybatis
MyBatis中Mapper接口和dao区别是什么?
MyBatis中Mapper接口和dao区别是什么?
|
1月前
|
SQL Java 数据库连接
MyBatis之魂:探索核心接口SqlSession的神秘力量
MyBatis之魂:探索核心接口SqlSession的神秘力量
27 3
MyBatis之魂:探索核心接口SqlSession的神秘力量
|
2月前
|
XML SQL Java
Mybatis接口Mapper内的方法为啥不能重载吗
Mybatis接口Mapper内的方法为啥不能重载吗
23 0
|
2月前
|
Java 数据库连接 mybatis
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
Mybatis+mysql动态分页查询数据案例——Mybatis的配置文件(mybatis-config.xml)
20 1
|
2月前
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
Mybatis+mysql动态分页查询数据案例——配置映射文件(HouseDaoMapper.xml)
17 1
|
2月前
Mybatis+mysql动态分页查询数据案例——房屋信息的接口(IHouseDao)
Mybatis+mysql动态分页查询数据案例——房屋信息的接口(IHouseDao)
14 1