我们正在JavaFx中开发一个新的桌面应用程序,其中对于脱机存储,我们使用的是SQLite,而对于orm,我们使用的是ormlite。ormlite JdbcPooledConnectionSource正确的用法
我想实现数据库连接池,其中应该在开始时设置固定数量的连接,并且应该根据需要使用,释放和重用。另外,如果我们能够恰当地使用“只读”和“只写”连接以最大限度地提高性能,那将是一件好事。
这就是我们迄今为止所写的内容。
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。
因此,有很多关于池连接源和重新使用连接的单元测试。你能否添加更多关于你为什么认为是这种情况的信息? https://github.com/j256/ormlite-jdbc/blob/master/src/test/java/com/j256/ormlite/jdbc/JdbcPooledConnectionSourceTest.java – Gray
此外,根据您使用的SQLite的数据库引擎,池连接源不会帮助你,因为SQLite通常是嵌入式的。池连接源实际上只对远程数据库有帮助。 – Gray
谢谢格雷!我们正在开发一个桌面应用程序(JavaFx),其中数据库没有嵌入,但是是分开的(SQLite文件)。我想要在ormlite中使用池连接的示例DAO设计模式。 –