javaormliteconnection-timeout

How to set timeout while creating connection in ormlite ConnectionSource?


The connection is created by the below method

import com.j256.ormlite.jdbc.JdbcConnectionSource;
import com.j256.ormlite.support.ConnectionSource;
ConnectionSource connectionSource =
    new JdbcConnectionSource(url + databaseName + "?currentSchema=trial&useSSL=false",
            userName, password);

Solution

  • How to set timeout while creating connection in ormlite ConnectionSource?

    Right now there is unfortunately no way to set a timeout on the connection. I would recommend using a database connection pool to give you this functionality. You can use Apache's DBCP, HikariCP, or others.

    To quote from the docs on pooled connection sources:

    There are many other, external data sources that can be used instead, including more robust and probably higher-performance pooled connection managers. You can instantiate your own directly and wrap it in the DataSourceConnectionSource class which delegates to it.

    // basic Apache data source
    BasicDataSource dataSource = new BasicDataSource();
    String databaseUrl = "jdbc:h2:mem:account";
    dataSource.setUrl(databaseUrl);
    // we wrap it in the DataSourceConnectionSource
    ConnectionSource connectionSource = 
       new DataSourceConnectionSource(dataSource, databaseUrl);