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