Search code examples
javaspringspring-jdbcjdbctemplate

Does JDBC template cache connection?


I have an java-spring web application, which will read, write and delete information from a user upload SQLite DB. I am using JDBCtemplate to set connection, query the DB and update the information.

I observed one behavior during my tests:

Every time,after users uploaded a new SQLite db file(it will has the same name, place at the same directory as the old DB file), if they do not reboot/restart tomcat, jdbcquery will report the db was corrupted exception.

To me this looked like the JDBCtemplate somehow cached the connection and is trying to resume the connection with the old db?

If so, do you know anyway to refresh the connection without rebooting the application?

final SingleConnectionDataSource dataSource = new singleConnectionDataSource();
try {
    Class.forName("org.sqlite.JDBC");
} catch (ClassNotFoundException e) {
        throw new applicationException(MessageTemplateNames.GENERAL_UNKNOWN_ERROR, e);
}

createDirectoryForDbIfNotExists();
dataSource.setUrl(String.format("%s%s", JDBC.PREFIX, getDbFileLocation()));
dataSource.setAutoCommit(true);

Solution

  • JDBCTemplate does not handle connection.It obtains the connection from the datasource set to it.

    From the reference documentation for SingleConnectionDataSource

    Implementation of SmartDataSource that wraps a single JDBC Connection which is not closed after use. .....

    This is primarily intended for testing. For example, it enables easy testing outside an application server, for code that expects to work on a DataSource. In contrast to DriverManagerDataSource, it reuses the same Connection all the time, avoiding excessive creation of physical Connections.

    A DriverManagerDataSource will suite your requirement to get a new connection without reboot

    Simple implementation of the standard JDBC DataSource interface, configuring the plain old JDBC DriverManager via bean properties, and returning a new Connection from every getConnection call.

    Update

    My answer might not solve your original problem , but will only answer the question for new connection without reboot. Please go through @Thilo's comment on the same.