如何在select子句中使用参数化列映射iBATIS的查询?

问题描述

| 我想拥有一种从数据库中特定表的列中查找特定值的方法,其中该列的名称作为参数传递。因此,Java方法将具有以下签名:
public Integer getFoo(String column) throws DataAccessException;
我对此查询的尝试映射如下:
<select id=\"getFoo\" parameterClass=\"java.lang.String\" resultClass=\"java.lang.Integer\">
    select min($column$) from daily_statistics where $column$ &gt; 0
</select>
这以一种有趣的方式失败了。如果我一次调用此方法,它将起作用。但是,如果我使用不同的列名两次调用它,则第二次调用将失败,并显示以下堆栈跟踪:
Caused by: com.ibatis.common.jdbc.exception.NestedSQLException:   
--- The error occurred in com/company/project/dao/ibatis/maps/FooBar.xml.  
--- The error occurred while applying a result map.  
--- Check the getSomething-AutoResultMap.  
--- Check the result mapping for the \'MIN(FIRST_COLUMN)\' property.  
--- Cause: java.sql.SQLException: Invalid column name
Caused by: java.sql.SQLException: Invalid column name
at com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryWithCallback(GeneralStatement.java:181)
at com.ibatis.sqlmap.engine.mapping.statement.GeneralStatement.executeQueryForObject(GeneralStatement.java:100)
at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForObject(SqlMapExecutorDelegate.java:561)
at com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate.queryForObject(SqlMapExecutorDelegate.java:536)
at com.ibatis.sqlmap.engine.impl.SqlMapSessionImpl.queryForObject(SqlMapSessionImpl.java:97)
at org.springframework.orm.ibatis.SqlMapClientTemplate$1.doInSqlMapClient(SqlMapClientTemplate.java:273)
at org.springframework.orm.ibatis.SqlMapClientTemplate.execute(SqlMapClientTemplate.java:209)
... 21 more
请注意,\'FIRST_COLUMN \'代表第一列的名称,即使该错误发生在第二次调用中,也从未发生在第一次调用中。 我发现以下映射不会给出错误,即使多次调用也是如此:
<select id=\"getFoo\" parameterClass=\"java.lang.String\" resultClass=\"java.lang.Integer\">
    select min(ANY_COLUMN) from daily_statistics where $column$ &gt; 0
</select>
因此,似乎该问题与在select子句中使用参数化列有关。     

解决方法

在SQL查询中使用别名。那应该解决将结果映射回java的问题。     

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...