我正在尝试使用 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