PSQLException:此连接已使用从DAO层传递的HashMap关闭



我有一种不好的感觉,我需要重构一些东西。本质上,我需要从 DAO 层的 PostgreSQL 中获取一个数组,然后将该 JDBC 数组转换为 String[] 或 Integer[] 数组。

我在这里的困惑是我不认为我引用了数据库连接或 ResultSet,所以我不知道为什么我会收到这个异常?

例外

当我尝试将 jdbc 数组转换为对象 [] 时,下面会抛出此异常。

org.postgresql.util.PSQLException: This connection has been closed.

道易普尔

public HashMap<String, Object> getUser(Integer id) {
try {
conn = DBConnectionFactory.getDatabaseConnection("postgresql");
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
map = generateMapFromResultSet(rs);
}
catch(Exception ex) {
ex.printStackTrace();
}
finally {
try {
if(conn != null) {
conn.close();
}
if(ps != null) {
ps.close();
}
if(rs != null) {
rs.close();
}
} 
catch (SQLException e) {
e.printStackTrace();
}
}
...
}
private HashMap<String, Object> generateMapFromResultSet(ResultSet rs) {
HashMap<String, Object> returnMap = null;
ResultSetMetaData rsmd = null; 
Integer columns = null;
try {
rsmd = rs.getMetaData();
columns = rsmd.getColumnCount();
while(rs.next()) {
returnMap = new HashMap<String,Object>(columns);
for(int index = 1; index <= columns; index++) {
returnMap.put(rsmd.getColumnName(index), rs.getObject(index));
}
}
}
catch(Exception ex) {
ex.printStackTrace();
}
return returnMap;               
}

服务层

这是采用HashMap的层,迭代HashMap,在我的DAO中执行比我想要的更多的逻辑并生成一个User对象。

private User convertMapToUser(HashMap<String,Object> userMap) throws IllegalArgumentException {
...
Iterator iterator = userMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry pair = (Map.Entry)iterator.next();
String columnName = (String)pair.getKey();
switch(columnName) {
case COLUMN1:
try {
Array col1_array = (Array)pair.getValue();
new_col1_array = (Integer[])col1_array.getArray(); //ERROR HERE!
}
catch(Exception ex) {
ex.printStackTrace();
}
break;
case COLUMN2:
try {
Array col2_array = (Array)pair.getValue();
new_col2_array = (Integer[])col2_array.getArray(); //ERROR HERE!
}
catch(Exception ex) {
ex.printStackTrace();
}
break;
default:
...
}
// avoids a ConcurrentModificationException
iterator.remove();
}
...
}

在DAO 层中使用 getArray 方法。

Object obj = rs.getObject(index);
if (obj instanceof Array)
{
obj = ((Array) obj).getArray();
}
returnMap.put(rsmd.getColumnName(index), obj);

最新更新