【mybatis踩坑】mybatis获取类型为字符串String的参数自动加引号-编程思维

今天写了一个简单的测试例子,用mybatis实现新建一个MySQL数据表

整体是JavaWeb项目,下面的代码是不完整的。

这是mapper

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3         PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4         "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 <mapper namespace="com.reliable.dao.CreateMapper">
 6     <update id="createTable3" parameterType="map">
 7         CREATE TABLE ${tableName} (
 8             field_1 VARCHAR(255) NOT NULL,
 9             field_2 VARCHAR(255) NOT NULL
10         )ENGINE=INNODB DEFAULT CHARSET=utf8;
11     </update>
12 </mapper>

测试

public void createTable3Test(ArrayList<String[]> tableInfo) {
        String tableName=tableInfo.get(0)[0]+"_state";
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("tableName",tableName);
        condition.put("comment_1","字段名");
        condition.put("comment_2","字段状态");
        System.out.println("第三张表名: "+condition.get("tableName"));
        SqlSession sqlSession = MybatisUtils.getSession();
        CreateMapper mapper = sqlSession.getMapper(CreateMapper.class);
        mapper.createTable3(condition);
        sqlSession.close();
    }

 

问题描述

当使用map向mapper传递参数时,在mapper接受这个参数有两种方式:

1、#{  } 

2、${  }

这两种方式有显著的区别:

#:默认会给传来的参数加上引号

$:不会给参数加任何东西

打个比方:

像我今天写的例子,如果表名的位置我传递的map的value是---表名1

如果使用#{ } 来接收参数,我的sql语句会变成这样, create table '表名1'  。。。

这样的话这个sql语句是有错误的,运行就会抛出异常

如果我使用${ } 来接收参数,我的sql语句是这样的,create table 表名1 。。。

这时候建表语句是没有问题的。

 

当参数需要加上引号的时候,用#{}。  

例:select * from xxx  where name= #{name}   

SQL:select * from xxx  where name= 'name'

 

当参数不需要加上引号的时候,用${}

例:select * from xxx order by ${id} 

 SQL:select * from xxx  order by id

版权声明:本文版权归作者所有,遵循 CC 4.0 BY-SA 许可协议, 转载请注明原文链接
https://www.cnblogs.com/rainbow-1/p/15589655.html