有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java或MLite JdbcPooledConnectionSource正确使用

我们正在用JavaFx开发一个新的桌面应用程序,其中脱机存储使用SQLite,orm使用ormlite

我想实现DB连接池,其中一个固定数量的连接应该在开始时设置,并且应该根据需要使用、释放和重用。此外,如果我们能够适当地使用“只读”和“写式”连接以最大限度地提高性能,那将是一件好事

这就是我们到目前为止所写的

public class DAO {
    private static JdbcPooledConnectionSource connectionSource;

    private static DAO instance = null;

    private DAO() throws SQLException {
        try {
            final File path = SystemUtils.getDatabaseFile();
            final String DATABASE_URL = Constants.DATABASE_URL + path.getAbsolutePath();

            Class.forName(Constants.DATABASE_DRIVER);

            connectionSource = new JdbcPooledConnectionSource(DATABASE_URL);
            //connectionSource.setMaxConnectionAgeMillis(5 * 60 * 1000);
            connectionSource.setCheckConnectionsEveryMillis(5000);
            connectionSource.setMaxConnectionsFree(5);
            connectionSource.initialize();
            init();
        } catch (ClassNotFoundException cnfe) {
            cnfe.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }   
    }

    private void init() throws ClassNotFoundException, SQLException {
        TableUtils.createTableIfNotExists(connectionSource, Customer.class);
        TableUtils.createTableIfNotExists(connectionSource, Address.class);
        TableUtils.createTableIfNotExists(connectionSource, Location.class);
        TableUtils.createTableIfNotExists(connectionSource, City.class);
        TableUtils.createTableIfNotExists(connectionSource, Area.class);
        TableUtils.createTableIfNotExists(connectionSource, Category.class);
        TableUtils.createTableIfNotExists(connectionSource, Product.class);
        TableUtils.createTableIfNotExists(connectionSource, AddonCategory.class);
        TableUtils.createTableIfNotExists(connectionSource, ProductAddon.class);

    }

    public synchronized <D extends Dao<T, ?>, T> D getDao(Class<T> cls) throws SQLException {
        Dao<T, ?> dao = DaoManager.createDao(connectionSource, cls);
        D daoImpl = (D) dao;

        return daoImpl;
    }

    public synchronized static DAO getInstance() throws SQLException {
        if (instance == null) instance = new DAO();
        return instance;
    }
}

这里的问题是,每次我们创建表(TableUtils.createTableIfNotExists)时,池连接源都在创建一个新连接,而不是重用先前使用/创建的连接

在Internet上找不到足够的关于如何正确使用JdbcPooledConnectionSource的代码示例


共 (1) 个答案

  1. # 1 楼答案

    JdbcPooledConnectionSource correct usage

    你在使用哪个SQLite驱动程序?Xerial驱动程序将Sqlite代码实际编译到Jar中。这意味着您实际上并不是“连接”到另一个数据库,而是直接调用该数据库,即使它前面有一个JDBC接口

    这意味着你真的不需要JdbcPooledConnectionSource。池连接只有在通过网络与数据库服务器建立连接时才有帮助。如果查看应用程序,您应该会看到文件描述符(在Linux中的/prod/#/fd If中),它显示打开的fd到数据库,但不到套接字

    The problem here is everytime we are creating table (TableUtils.createTableIfNotExists) the pooled connection source is making a new connection and not reusing the one earlier used/created.

    人力资源管理。我在池连接源的单元测试中有一些很好的报道。听说它没有重用连接,我很惊讶。你能给我一个单元测试来演示一下吗