【问题标题】:Managing transactions in JavaSE with Hibernate and Guice在 JavaSE 中使用 Hibernate 和 Guice 管理事务
【发布时间】:2011-03-13 07:01:20
【问题描述】:

我正在编写一个相当简单的应用程序,它使用 GWT、Hibernate 和 Google Guice(使用 GIN)。我想做的是使用外部管理器管理事务(例如在 Spring 中使用 @Transactional),而不是使用 EntityManager#getTransaction。我尝试使用@Transactional,但它似乎对我不起作用。

我已经使用 Providers 注入了 EntityManager,如下所示:

/* import stuff */

public class DbProvider implements Provider<EntityManager> {

    public EntityManager get() {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("persdb");
        return emf.createEntityManager();
    }

}

手动管理事务时似乎可以正常工作。我想自动管理事务,也为了使用 DBUnit 进行自动化测试。

有人知道怎么解决吗?

【问题讨论】:

    标签: java hibernate transactions guice


    【解决方案1】:

    @Transactional在Guice工作requires three things

    • 你的类路径中需要guice-persist.jar
    • 调用@Transactional方法的对象必须由Guice创建
    • 方法不能是private

    【讨论】:

    • 非常感谢!如果只有这样的话:) 你在哪里启动 PersistService?
    • @halish:您可以在任何地方启动PersistService(例如,当您的应用程序启动时)。在 Web 应用程序中,可以使用 PersistFilter 来完成,它会在创建服务时启动服务,并在销毁时停止服务。在您自己的应用程序中,您需要先启动它,然后再执行任何使用它的操作。
    猜你喜欢
    • 2017-10-30
    • 2020-12-07
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-04
    • 2012-10-16
    • 2017-10-03
    相关资源
    最近更新 更多