首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JPA事务在没有Guice/Spring的情况下不那么痛苦

JPA事务在没有Guice/Spring的情况下不那么痛苦
EN

Stack Overflow用户
提问于 2012-04-13 21:16:12
回答 4查看 1.5K关注 0票数 4

Spring和Guice-persist都允许在访问数据库的方法上进行@Transactional注释,以便在没有打开事务时自动创建事务,在方法返回时提交事务,在异常时回滚等。

有没有办法在OSGi应用程序中不使用Spring或Guice就能获得相同的东西(或类似的可用性)?

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-04-14 00:14:26

Apache Aries允许您在blueprint.xml中以声明方式配置事务。例如:

代码语言:javascript
复制
<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框架中。

票数 2
EN

Stack Overflow用户

发布于 2012-04-14 03:22:54

我有以下代码片段,即使在Guice/Spring @Transactional容器中运行时,我也经常使用它们:

代码语言:javascript
复制
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();
        }
    }
}

用法:

代码语言:javascript
复制
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();
    }
});

它非常轻量级,可以完成工作。

票数 4
EN

Stack Overflow用户

发布于 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?中找到。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10141553

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档