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语法错误的问题。