How to map query for iBATIS with parameterized column in select clause?
I want to have a method that finds a certain value from a column of a particular table in the database, where the name of the column is passed in as a parameter. So the Java method would have the following signature:
public Integer getFoo(String column) throws DataAcce开发者_如何转开发ssException;
My attempted mapping for this query is the following:
<select id="getFoo" parameterClass="java.lang.String" resultClass="java.lang.Integer">
select min($column$) from daily_statistics where $column$ > 0
</select>
This fails in an interesting way. If I call this method once, it works. But if I call it twice with different column names, the second call fails with the following stack trace:
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
Note that 'FIRST_COLUMN' represents the name of the first column, even though the error occurs on the second call, never on the first call.
I have discovered that the following mapping will not give errors, even when called multiple times:
<select id="getFoo" parameterClass="java.lang.String" resultClass="java.lang.Integer">
select min(ANY_COLUMN) from daily_statistics where $column$ > 0
</select>
So it seems that the problem is related to the use of a parametrized column in the select clause.
Use an alias in the SQL query. That should solve the problem of mapping the result back to java.
精彩评论