我想創建一個方法來動態創建表格,只需將表格名稱作爲變量傳遞。 我定義我的XML映射使用MyBatis和MySql以編程方式創建表格
<mapper namespace="com.mappers.TableCreatorMapper">
<cache />
<insert id="createNewTableIfNotExists" parameterType="String" >
CREATE TABLE IF NOT EXISTS #{tableName}
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB
</insert>
</mapper>
而且我的Java接口映射很簡單:
public interface TableCreatorMapper {
public void createNewTableIfNotExists(String tableName);
}
,但是當我把我的界面
tableCreatorMapper.createNewTableIfNotExists("test");
我得到以下異常:
org.springframework.jdbc.BadSqlGrammarException:
### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test'
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
' at line 1
### The error may involve com.mappers.TableCreatorMapper.createNewTableIfNotExists-Inline
### The error occurred while setting parameters
### SQL: CREATE TABLE IF NOT EXISTS ? ( `ID` varchar(20) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB
### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test'
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
' at line 1
; bad SQL grammar []; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''test'
(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
' at line 1
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:231)
at org.sp
如果我不是更改查詢添加``表名:
CREATE TABLE IF NOT EXISTS `#{tableName}`(
`ID` varchar(20) NOT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB
我得到
### The error occurred while setting parameters
### SQL: CREATE TABLE IF NOT EXISTS `?`( `ID` varchar(20) NOT NULL, PRIMARY KEY (`ID`) ) ENGINE=InnoDB
### Cause: java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
; SQL []; Parameter index out of range (1 > number of parameters, which is 0).; nested exception is java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
任何想法,爲什麼?
您好,感謝您的建議,但隨後我會得到: org.mybatis.spring.MyBatisSystemException:嵌套的例外是org.apache.ibatis.reflection.ReflectionException:沒有消氣財產名爲「表名」中'class java.lang.String' \t at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:75) – MarMan
請嘗試更新的答案;如果它不起作用,簡單的[binding](https://mybatis.github.io/mybatis-3/dynamic-sql.html)應該可以工作。 – agad
謝謝! $ {_ parameter}就像一個魅力! – MarMan