除非您别无选择,否则我不会推荐这种解决方案。二级缓存不可能与这样的解决方案一起使用,但它是一种(稳定的)解决方案,我被迫使用它来争取时间,直到将底层遗留数据库合并为一个。
首先在 JBoss Standalone.xml 中将您的数据库连接设置为 XA 数据源。如果使用 MS SQL 服务器,请按照http://msdn.microsoft.com/en-us/library/aa342335.aspx上的说明如何正确设置 XA
独立的.xml
<datasources>
<datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
<connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</connection-url>
<driver>h2</driver>
<security>
<user-name>sa</user-name>
<password>sa</password>
</security>
</datasource>
<xa-datasource jta="true" jndi-name="java:jboss/datasources/MYDB_ONE" pool-name="MYDB_ONE" enabled="true" use-java-context="true" use-ccm="true">
<xa-datasource-property name="ServerName">
localhost
</xa-datasource-property>
<xa-datasource-property name="DatabaseName">
MYDB_ONE
</xa-datasource-property>
<xa-datasource-property name="SelectMethod">
cursor
</xa-datasource-property>
<xa-datasource-class>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xa-datasource-class>
<driver>sqljdbc</driver>
<xa-pool>
<is-same-rm-override>false</is-same-rm-override>
</xa-pool>
<security>
<user-name>some_user</user-name>
<password>some_password</password>
</security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker"/>
</validation>
</xa-datasource>
<xa-datasource jta="true" jndi-name="java:jboss/datasources/MYDB_TWO" pool-name="MYDB_TWO" enabled="true" use-java-context="true" use-ccm="true">
<xa-datasource-property name="ServerName">
localhost
</xa-datasource-property>
<xa-datasource-property name="DatabaseName">
MYDB_TWO
</xa-datasource-property>
<xa-datasource-property name="SelectMethod">
cursor
</xa-datasource-property>
<xa-datasource-class>com.microsoft.sqlserver.jdbc.SQLServerXADataSource</xa-datasource-class>
<driver>sqljdbc</driver>
<xa-pool>
<is-same-rm-override>false</is-same-rm-override>
</xa-pool>
<security>
<user-name>some_user</user-name>
<password>some_password</password>
</security>
<validation>
<valid-connection-checker class-name="org.jboss.jca.adapters.jdbc.extensions.mssql.MSSQLValidConnectionChecker"/>
</validation>
</xa-datasource>
<drivers>
<driver name="h2" module="com.h2database.h2">
<xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
</driver>
<driver name="sqljdbc" module="com.microsoft.sqlserver.jdbc">
<driver-class>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver-class>
</driver>
<driver name="postgresql" module="org.postgresql">
<xa-datasource-class>org.postgresql.xa.PGXADataSource</xa-datasource-class>
</driver>
</drivers>
</datasources>
然后我设置了我的 entityManager bean,它使用我的 AbstractRoutingDataSource 实现作为它的数据源。这是 Spring 驱动的 JPA 设置,不使用 persistence.xml 文件;据我所知,这是使用 JBoss 7 时自动扫描实体包的唯一方法。
springJpaConfig.xml
<!-- Use @PersistenceContext annotations for injecting entity managers -->
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<!-- Set up JTA transaction manager -->
<tx:jta-transaction-manager />
<bean id="entityManagerFactoryMyDB" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="MyDB" />
<property name="dataSource" ref="dataSourceMyDB" />
<property name="packagesToScan" value="my.package.with.jpa.entities" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
</bean>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="javax.persistence.transactionType" value="jta" />
<entry key="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossAppServerJtaPlatform" />
<entry key="jboss.entity.manager.factory.jndi.name" value="java:app/MyDBEntityManagerFactory" />
<entry key="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect" />
</map>
</property>
</bean>
<bean id="dataSourceMyDB" class="some.package.AbstractRoutingDataSourceMyDB">
<property name="lenientFallback" value="false" />
<property name="defaultTargetDataSource" value="java:jboss/datasources/ExampleDS" />
<property name="targetDataSources">
<map key-type="String">
<!-- This is a placeholder that will be filled in by BeanFactoryPostProcessor -->
</map>
</property>
</bean>
<!-- This allows us to modify Spring configuration load the list of datasources -->
<bean class="some.package.DatasourceRegisteringBeanFactoryPostProcessor" />
我在 AbstractRoutingDataSourceMyDB 中使用 ExampleDS 作为默认值,因为您必须提供一个 defaultTargetDataSource,但我总是想手动选择一个有效的数据库,因此如果有人在没有先手动选择连接的情况下尝试访问数据库,他们将尝试在不存在的 ExampleDS 数据库,它将引发异常(非常 hacky,但它完成了工作)。
在 BeanFactoryPostProcessor 中,我现在需要填写我的数据源列表:
数据源RegisteringBeanFactoryPostProcessor.java
package some.package
class DatasourceRegisteringBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
HashMap<String, String> connectionsListMyDB = new HashMap<>();
// Load your connection list from wherever you need to, you can
// enumerate them directly from JNDI or some configuration location
connectionsListMyDB.put("db1", "java:jboss/datasources/MYDB_ONE");
connectionsListMyDB.put("db2", "java:jboss/datasources/MYDB_TWO");
if (connectionsList.isEmpty())
throw new RuntimeException("No JPA connections defined");
// Configure the dataSource bean properties
BeanDefinitionRegistry factory = (BeanDefinitionRegistry) beanFactory;
MutablePropertyValues mpv = factory.getBeanDefinition("dataSourceMyDB").getPropertyValues();
ManagedMap<String, String> mm = (ManagedMap<String, String>) mpv.getPropertyValue(
"targetDataSources").getValue();
mm.clear();
for (Entry<String, String> e : connectionsListMyDB.entrySet()) {
mm.put(e.getKey(), e.getValue());
}
}
}
这是我的 AbstractRoutingDataSource 实现,它允许我在运行时切换连接:
AbstractRoutingDataSourceMyDB.java
public class AbstractRoutingDataSourceMyDB extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return getDbConnectionMyDB();
}
// ThreadLocal variable so that the connection gets set for the current thread
// using spring's request scope on the class instead of ThreadLocal would also work here.
private final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public void setDbConnectionMyDB(String myKey) {
Assert.notNull(myKey, "myKey cannot be null");
contextHolder.set(myKey);
String k = contextHolder.get();
}
public String getDbConnectionMyDB() {
return (String) contextHolder.get();
}
public void clearDbConnectionMyDB() {
contextHolder.remove();
}
}
请注意,在您从 DAO 类中更改当前连接之前,您必须调用 entitymanager.flush() 和 clear(),否则该事务范围内的所有挂起操作将在事务提交时在新连接上执行。这是因为 Hibernate 会话忘记了连接曾经改变过,据它所知 - 它始终是同一个数据库。
所以在你的 DAO 中你现在可以这样做:
SomeTableDAO.java
@PersistenceContext(unitName = "MyDB")
private EntityManager em;
@Autowired
private AbstractRoutingDataSourceMyDB routingSource;
public void someMethod(int id) {
em.flush();
em.clear();
routingSource.setDbConnectionMyDB("db1");
em.remove(em.getReference(Something.class, id)); // delete something in db1
em.flush();
em.clear();
routingSource.setDbConnectionMyDB("db2");
em.remove(em.getReference(Something.class, id)); // delete something else with the same id in db2
}
所以你去吧,虽然它不漂亮 - 它可以完成:)