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语法错误的问题。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能