我有一种不好的感觉,我需要重构一些东西。本质上,我需要从DAO层中的PostgreSQL中获取一个数组,然后将该JDBC数组转换为String []或Integer []数组。
我在这里的困惑是我不认为我引用数据库连接或ResultSet,所以我不知道为什么我会得到这个例外?:
异常
当我尝试将jdbc数组转换为Object []时,抛出此异常。
org.postgresql.util.PSQLException: This connection has been closed.
DAOImpl
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;
}
ServiceLayer
这是获取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();
}
...
}
答案 0 :(得分:0)
在DAO层中使用getArray方法。
Object obj = rs.getObject(index);
if (obj instanceof Array)
{
obj = ((Array) obj).getArray();
}
returnMap.put(rsmd.getColumnName(index), obj);