添加ALIAS_COLUMN_NAME = TRUE到JDBC URL 應該意味着H2允許「別名」中列名,即你可以這樣做:H2數據庫ALIAS_COLUMN_NAME = TRUE似乎沒有奏效
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
您列出的測試用例不使用'd.name'。你能更新測試用例或異常堆棧跟蹤嗎? –
哈哈。感謝和發現!錯誤的堆棧跟蹤。來自原始問題,而不是示例。已修復。 –