0

I'm using Jersey as WebService and Hibernate EntityManager to persist my data...

The persistence will work correctly if I write my method as this :

@GET @Path("/") public Response test() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1"); EntityManager em = emf.createEntityManager(); Test product = new Test("desc"); em.getTransaction().begin(); if (!em.contains(product)) { em.persist(product); em.flush(); } em.getTransaction().commit(); em.close(); emf.close(); return Response.status(Response.Status.OK).build(); } 

However I want to use the @Transactional from com.google.inject.persist.Transactional to make the code more light :

@GET @Transactional @Path("/") public Response test() { EntityManagerFactory emf = Persistence.createEntityManagerFactory("manager1"); EntityManager em = emf.createEntityManager(); Test product = new Test("desc"); em.persist(product); em.close(); emf.close(); return Response.status(Response.Status.OK).build(); } 

However with this code the data are not recorded into the database !

Any Idea

2
  • Have you defined TransactionalManager? Commented Jul 17, 2016 at 11:38
  • No because i'm not using Spring .. I want to use Guice instead Commented Jul 17, 2016 at 12:48

1 Answer 1

1

In the code you are missing

em.flush(); 

Two more suggestions:

1) Let Guice manage the entity manager. Inject it, do not create the EntityManager instance yourself.

public class ProductDao { @Inject private EntityManager em; public Product find(Long id) { return em.find(Product.class, id); } @Transactional public void save(Product entity) { em.persist(entity); } } 

note: I am not familiar with Guice, but I know Spring.

2) Use layered design. Separate application code into controller, domain, service and persistence layers.

Persistence layer is used to access data. Move all classes which use EntityManager methods to persistence (data access) layer.

Service layer is for controlling transactions.

Domain layer is for entities and entity-specific business logic.

Controller layer is for request mapping and marshalling. Use request mapping annotations @Get, @Path("/") here.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.