Spring和Guice-persist都允许在访问数据库的方法上进行@Transactional注释,以便在没有打开事务时自动创建事务,在方法返回时提交事务,在异常时回滚等。
有没有办法在OSGi应用程序中不使用Spring或Guice就能获得相同的东西(或类似的可用性)?
发布于 2012-04-14 00:14:26
Apache Aries允许您在blueprint.xml中以声明方式配置事务。例如:
<blueprint
xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
xmlns:jpa="http://aries.apache.org/xmlns/jpa/v1.0.0"
xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.0.0">
<bean
id="transactedBean"
class="some.package.BeanImpl">
<tx:transaction
method="*"
value="Required" />可以将白羊座捆绑包放入您选择的OSGi框架中。
发布于 2012-04-14 03:22:54
我有以下代码片段,即使在Guice/Spring @Transactional容器中运行时,我也经常使用它们:
public void transact(Runnable runnable) {
EntityTransaction tx = em.getTransaction();
boolean success = false;
tx.begin();
try {
runnable.run();
success = true;
} finally {
if (success) {
tx.commit();
} else {
tx.rollback();
}
}
}
public <T> T transact(Callable<T> callable) throws Exception {
EntityTransaction tx = em.getTransaction();
boolean success = false;
tx.begin();
try {
T result = callable.call();
success = true;
return result;
} finally {
if (success) {
tx.commit();
} else {
tx.rollback();
}
}
}用法:
dao.transact(new Runnable() {
public void run() {
// do stuff in JPA
}
});
Long count = dao.transact(new Callable<Long>() {
public Long call() {
return em.createQuery("select count(*) from Foo", Long.class)
.getSingleResult();
}
});它非常轻量级,可以完成工作。
发布于 2012-04-13 22:46:42
一种可能的解决方案是使用Spring Data JPA,因为它使用JpaRepositoryFactory作为RepositoryFactorySupport进行can be used outside Spring container。有关如何使其正常工作的有用信息可在How do you use Spring Data JPA outside of a Spring Container?中找到。
https://stackoverflow.com/questions/10141553
复制相似问题