将 ALIAS_COLUMN_NAME=TRUE 添加到 JDBC url应该意味着 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