今天寫了一個簡單的測試例子,用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