【发布时间】:2011-08-05 10:48:27
【问题描述】:
是否可以将 Hibernate/JPA 配置为在独立环境中使用 OracleDataSource?更具体地说,我要做的是通过persistence.xml文件配置oracle隐式连接缓存。这可能吗?
提前致谢 布赖恩
【问题讨论】:
是否可以将 Hibernate/JPA 配置为在独立环境中使用 OracleDataSource?更具体地说,我要做的是通过persistence.xml文件配置oracle隐式连接缓存。这可能吗?
提前致谢 布赖恩
【问题讨论】:
我最近在一个使用 MySQL 的 JSE 应用程序中解决了一个类似的问题。与您的情况一样,我需要它来使用现有的连接提供程序。
就我而言,我使用了Apache Commons DBCP。这个连接池框架允许我在数据源上创建一个连接池,然后在一个假驱动程序名称下注册该池,您可以在 persistence.xml 文件中的 JPA 配置中使用该名称。
我就是这样做的。首先,我根据原始数据源注册了一个连接池,并为这个给定的池注册了一个假驱动程序。
private ObjectPool getNewConnectionPool(DataSource mySqlDataSource) {
try {
GenericObjectPool pool = new GenericObjectPool(null, 10);
pool.setTestOnBorrow(true);
ConnectionFactory factory = new DataSourceConnectionFactory(mySqlDataSource);
PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(factory, pool, null, "SELECT 1 FROM DUAL", false, true);
Class.forName("org.apache.commons.dbcp.PoolingDriver");
PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
driver.registerPool("myPool", pool);
return poolableConnectionFactory.getPool();
} catch (Exception e) {
throw new RuntimeException("Unable to initialize connetion pooling", e);
}
}
然后,我不再使用原始数据源,而是从现在开始继续使用池化数据源。
DataSource dataSource = new PoolingDataSource(getNewConnectionPool(mySqlDataSource));
到目前为止,您已经有了一个基于原始数据源的功能数据源,您可以从中获取连接。您还可以通过为此池注册的虚假驱动程序获取连接,这些连接也将来自原始数据源。
Connection conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:myPool");
不仅如此,您还可以在您的 persistence.xml 文件中使用此 URL 来配置 JPA 的连接源,或者在您创建它时提供给 EntityManagerFactory 的属性中。
Map<String, Object> properties = new HashMap<String, Object>();
properties.put("javax.persistence.provider", "org.hibernate.ejb.HibernatePersistence");
properties.put("javax.persistence.jdbc.url", "jdbc:apache:commons:dbcp:myPool");
this.entityManagerFactory = Persistence.createEntityManagerFactory("myUnit", properties);
this.entityManager = this.entityManagerFactory.createEntityManager();
使用此 JDBC URL,您现在可以访问池中的连接,并通过它访问原始数据源。
【讨论】: