Domanda

I am trying to create a simple service class with a @Transactional annotated method using Guice Persist:

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();
    }

}

Unfortunately no transaction is created by Guice Persist. Log output can be seen here: http://pastebin.com/Mh5BkqSC

Note the print on line 450:

Is transaction active? false

The result is that nothing is stored in the database:

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=# 

I setup the application in the following way:

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);
}

As you can see TestService is created by Guice, and I am using the JpaPersistModule, which should be what does the @Transactional wiring.

I have created a small Maven project demonstrating the problem: https://github.com/uldall/guice-persist-error

È stato utile?

Soluzione

The problem was resolved by switching from @javax.transaction.Transactional to @com.google.inject.persist.Transactional. Apparently Guice-Persist doesn't support the @Transactional annotation from the Java Transaction API.

Altri suggerimenti

I have used without @Transactional annotation and it worked:

    entityManager.getTransaction().begin();
    entityManager.persist(entity);
    entityManager.getTransaction().commit();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top