我使用的是glassfish 4和java EE 7,我需要为将要在glassfish中部署的每个应用程序定义一个不同的连接池。
我的每个客户端都有一个应用程序(.war文件),并且每个客户端在mysql数据库中都有自己的用户/密码/模式,因此数据不会在客户端之间共享。我知道如何在glassfish中定义连接池,但是我的所有应用程序都只能使用相同的设置(我使用bonecp btw)。我希望能够为部署的每个应用程序更改用户/密码/模式。是否可以在persistence.xml中完全定义连接池,而不是在glassfish中,这样我就可以在不同的.war文件中有一个不同的连接池?部署了10个.war文件(10个客户端)后,我希望有10个不同的连接池(定义了不同的用户/密码/模式)。
发布于 2014-11-21 23:06:05
如果您以编程方式创建数据源,则可以将其注入到JPA中,而无需在persistence.xml中声明它。下面是一个例子
定义persistence-xml:
<persistence-unit name="foo-PU" transaction-type="RESOURCE_LOCAL">
<!-- the provider: Hibernate, EclipseLink or another -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<!-- No need to define any connection parameter nor the data source -->
<!-- class definitions here -->
</persistence-unit>
定义.properties文件以存储数据源的配置:
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/foo_db
db.user=user
db.password=s3cr3t
db.bonecp.idleConnectionTestPeriod=60
db.bonecp.idleMaxAge=240
db.bonecp.maxConnections=10
# more properties...
定义将生成数据源的类
public class DataSourceGenerator {
public static DataSource getDataSource(String properties) {
Properties conf = new Properties();
try {
conf.load(
DataSourceFactory.class
.getClassLoader().getResourceAsStream(
properties));
} catch (IOException e) {
//handle the error
//naive handling shown here
e.printStacktrace();
}
BoneCPDataSource dataSource = new BoneCPDataSource();
//set the properties from the .properties file
dataSource.setDriverClass(conf.getProperty("db.driver"));
dataSource.setJdbcUrl(conf.getProperty("db.url"));
dataSource.setUsername(conf.getProperty("db.user"));
dataSource.setPassword(conf.getProperty("db.password"));
dataSource.setIdleConnectionTestPeriodInMinutes(
Long.parseLong(
conf.getProperty("db.bonecp.idleConnectionTestPeriod")));
dataSource.setIdleMaxAgeInSeconds(
Long.parseLong(
conf.getProperty("db.bonecp.idleMaxAge")));
dataSource.setMaxConnectionsPerPartition(
Integer.parseInt(
conf.getProperty("db.bonecp.maxConnections")));
//more properties to load...
return dataSource;
}
}
也可以通过编程方式创建EntityManagerFactory
:
public class EntityManagerFactoryGenerator {
public static EntityManagerFactory createEMF() {
Map<String, Object> properties = new HashMap<>();
String dataSourceKey = "";
//uncomment here depending on your needs...
//using Hibernate
//dataSourceKey = org.hibernate.cfg.AvailableSettings.DATASOURCE;
//using EclipseLink
//dataSourceKey = org.eclipse.persistence
// .config.PersistenceUnitProperties.NON_JTA_DATASOURCE;
properties.put(
dataSourceKey,
DataSourceGenerator.getDataSource("mysql-con.properties"));
return Persistence.createEntityManagerFactory("foo-PU", properties);
}
}
发布于 2014-11-23 10:49:21
步骤1.转到Glassfish管理控制台配置JDBC连接详细信息。
内部资源- JDBC为每组连接细节创建一个池,然后为每个创建的池创建一个JDBC数据源。
步骤2.转到每个应用程序的持久性文件,并指向正确的数据源。
如果您不需要任何特殊的东西,请不要指定提供者,因为Glassfish已经随EclipseLink一起提供了,这很好用。
https://stackoverflow.com/questions/27071627
复制