@Transactional注释未启动事务(Guice Persist)

时间:2014-03-04 09:22:49

标签: java hibernate jpa transactions guice-persist

我正在尝试使用Guice Persist创建一个带有@Transactional注释方法的简单服务类:

public class TestServiceImpl implements TestService {

    @Inject
    private Provider<EntityManager> entityManager;

    @Override
    @Transactional
    public Long createEvent(String name) {
        Event event = new Event(name);

        System.out.println("Is transaction active? " + entityManager.get().getTransaction().isActive() );

        entityManager.get().persist(event);

        return event.getId();
    }

}

遗憾的是,Guice Persist没有创建任何交易。日志输出可以在这里看到:http://pastebin.com/Mh5BkqSC

请注意第450行的打印:

  

交易是否有效?假

结果是数据库中没有存储任何内容:

mydb=# \d
                 List of relations
 Schema |        Name        |   Type   |  Owner   
--------+--------------------+----------+----------
 public | events             | table    | postgres
 public | hibernate_sequence | sequence | postgres
(2 rows)

mydb=# select * from events;
 id | name 
----+------
(0 rows)

mydb=# 

我按以下方式设置应用程序:

public static void main(String[] args) {
    Injector injector = Guice.createInjector(new TestModule(), new JpaPersistModule("postgresPersistenceUnit"));

    PersistService persistService = injector.getInstance(PersistService.class);
    persistService.start();

    TestService serviceToTest = injector.getInstance(TestService.class);

    Long id = serviceToTest.createEvent("test");

    System.out.println("Id: " + id);
}

正如您所看到的,TestService是由Guice创建的,而我使用的是JpaPersistModule,这应该是@Transactional布线的内容。

我创建了一个小型Maven项目来演示问题:https://github.com/uldall/guice-persist-error

2 个答案:

答案 0 :(得分:7)

@javax.transaction.Transactional切换到@com.google.inject.persist.Transactional解决了问题。显然,Guice-Persist不支持Java Transaction API中的@Transactional注释。

答案 1 :(得分:1)

我使用了没有@Transactional注释并且它起作用了:

    entityManager.getTransaction().begin();
    entityManager.persist(entity);
    entityManager.getTransaction().commit();