MyBatis之动态修改功能

通常我们使用原生的sql进行动态修改的时候,经常会出现SQL的语法错误,而要规避这些存在的语法错误需要大量的代码来进行判断,而MyBatis的<set>标签就很好的解决了这个问题。

下面是我的源代码

复制代码
 <update id="updatedongtai">
        update tb_brand
        <set>
            <if test="companyName != null and companyName != '' ">company_name = #{companyName},</if>
            <if test="brandName != null and brandName != '' ">brand_name = #{brandName},</if>
            <if test="ordered != null and ordered != '' ">ordered = #{ordered},</if>
            <if test="description != null and description != '' ">description = #{description},</if>
            <if test="status != null and status != '' ">status = #{status}</if>
        </set>
        where id = #{id};
    </update>
复制代码

如果不用<set>,可能遇到的问题是用户没输入最后一个status字段,拼接sql的时候会没用status,会有,在where前面,会造成SQL语法错误。解决方法就是用<set></set>。

 

复制代码
package com.wjb.test;
import com.wjb.mapper.BrandMapper;
import com.wjb.pojo.Brand;
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 org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

public class MyBatisTestupdate {

    @Test
    public void testupdate() throws IOException {

        int status = 1;
        String companyName = "bo导手机";
        String brandName = "bo导";
        String description =  "bo导,改变世界";
        int ordered = 300;
        int id = 8;
        //封装对象

        Brand brand = new Brand();
        //brand.setBrandName(brandName);
        //brand.setStatus(status);
        //brand.setCompanyName(companyName);
        //brand.setDescription(description);
        brand.setOrdered(ordered);
        brand.setId(id);
        //1.加载mybatis的核心配置文件,获取SqlSessionFactory
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2.获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession(true);

        //3.获取Mapper接口的代理对象
        BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

        //4.执行方法

        brandMapper.updatedongtai(brand);

        //5.释放资源
        sqlSession.close();
    }

}
复制代码

在日志中我们可以看到拼接的SQL是这样的

 

 完美解决了sql语法错误的问题。

posted @   权。  阅读(561)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示