Spring Jdbctemplate with PostgreSQL: connection already closed when accesing java.sql.Array

StackOverflow https://stackoverflow.com/questions/21752386

Frage

I am using the Spring's JdbcTemplate with PostgreSQL. When my application comes to executing the below lines of code, an error is thrown. The method contains other read-only query-executions chained in a row, before it comes to that particular line.

The jdbcTemplate seems to close the connection, before the java.sql.Array can be extacted from the Map.

public void writeGeoRelation(Long id){

    ...

    List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
    for (Map<String, Object> map : list) {
        Long[] arr = (Long[]) ((Array) map.get("foo")).getArray(); //Erroneous line
    }
}

This is the stack trace:

org.postgresql.util.PSQLException: This connection has been closed.
    at org.postgresql.jdbc2.AbstractJdbc2Connection.checkClosed(AbstractJdbc2Connection.java:822)
    at org.postgresql.jdbc3.AbstractJdbc3Connection.prepareStatement(AbstractJdbc3Connection.java:273)
    at org.postgresql.jdbc2.AbstractJdbc2Connection.prepareStatement(AbstractJdbc2Connection.java:301)
    at org.postgresql.jdbc2.TypeInfoCache.getArrayDelimiter(TypeInfoCache.java:337)
    at org.postgresql.jdbc2.AbstractJdbc2Array.buildArrayList(AbstractJdbc2Array.java:372)
    at org.postgresql.jdbc2.AbstractJdbc2Array.getArrayImpl(AbstractJdbc2Array.java:160)
    at org.postgresql.jdbc2.AbstractJdbc2Array.getArray(AbstractJdbc2Array.java:128)
    at com.company.geo.director.GeoDirector.writeGeoRelation(GeoDirector.java:438)

Do you know how I can force the connection to stay open without regressing to plain Jdbc? I'd really like to stay with Spring Jdbc.

War es hilfreich?

Lösung

You might consider using @Transactional over your methods in DAO or Service from where the DAO is being called.

Transactions ensures the atomicity of the sequence of operations. That precisely means, either everything is successful or in case of exception all the queries are rolled back. When there is a failure in the transaction, Spring closes the connection and releases the resource. If there is no transaction, then no one guarantees when the connection is closed ( It might also get closed after one call returns successfully from the DB and for the next call another connection might be acquired.

As you state that the problem is solved, I stop writing here, for more on Spring refer my blog:TechieMe

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top