将ALIAS_COLUMN_NAME = TRUE添加到JDBC网址应该意味着h2允许列名中的“别名”,即您可以这样做:
resultSet.getString("p.first_name")
如果p是某个表的别名。对于我来说,这似乎并不适用,如此代码所示:
package com.example;
import junit.framework.TestCase;
import org.apache.commons.dbcp.BasicDataSource;
import org.h2.Driver;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
/**
* H2 Spring Test
*/
public class H2SelectTest extends TestCase {
public void testQuery() throws Exception {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName(Driver.class.getName());
dataSource.setUrl("jdbc:h2:mem:test;ALIAS_COLUMN_NAME=TRUE");
dataSource.setUsername("sa");
dataSource.setPassword("");
JdbcTemplate template = new JdbcTemplate(dataSource);
template.afterPropertiesSet();
template.execute("create table people(id int auto_increment, first_name varchar);");
SimpleJdbcInsert insert = new SimpleJdbcInsert(template).withTableName("people");
insert.setGeneratedKeyName("id");
insert.compile();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("first_name", "Bob");
insert.execute(map);
template.query("select p.first_name from people p", new RowCallbackHandler() {
public void processRow(ResultSet rs) throws SQLException {
String name = rs.getString("p.first_name");
}
});
}
}
导致此错误:
Caused by: org.h2.jdbc.JdbcSQLException: Column "p.first_name" not found [42122-168]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:169)
at org.h2.message.DbException.get(DbException.java:146)
at org.h2.jdbc.JdbcResultSet.getColumnIndex(JdbcResultSet.java:2918)
at org.h2.jdbc.JdbcResultSet.get(JdbcResultSet.java:2979)
at org.h2.jdbc.JdbcResultSet.getString(JdbcResultSet.java:291)
at org.apache.commons.dbcp.DelegatingResultSet.getString(DelegatingResultSet.java:225)
at com.example.H2SelectTest$1.processRow(H2SelectTest.java:35)
at org.springframework.jdbc.core.JdbcTemplate$RowCallbackHandlerResultSetExtractor.extractData(JdbcTemplate.java:1482)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:446)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:396)
... 19 more
答案 0 :(得分:3)
以下是您正在寻找的答案:
根据这些文档,ALIAS_COLUMN_NAME适用于不是表别名的列名:
/**
* System property <code>h2.aliasColumnName</code>.<br />
* When enabled, aliased columns (as in SELECT ID AS I FROM TEST) return the
* alias (I in this case) in ResultSetMetaData.getColumnName() and 'null' in
* getTableName(). If disabled, the real column name (ID in this case) and
* table name is returned. This setting only affects the default mode.
**/
事实证明,使用表别名查询结果集仅由MySQL支持,并且JDBC规范不支持。您可以使用H2中的完整表名来消除列的歧义,例如resultSet.getString(“people.first_name”)但是我担心,如果你使用h2对你通常针对MySQL运行的代码进行内部测试,你必须找到另一种方法(例如,不要别名和使用全表名称。)
如果您需要任何其他帮助,请告诉我,请给我留言。