Jersey, Guice and Hibernate - EntityManager thread safety

后端 未结 3 695
轮回少年
轮回少年 2021-01-17 05:40

I have used this tutorial them same way in my application: http://www.benmccann.com/hibernate-with-jpa-annotations-and-guice/

My app is JAX-RS web service which will

3条回答
  •  清歌不尽
    2021-01-17 05:50

    The problem was that my endpoint was annotated with @Singleton so it reused the same EntityManager during concurrent calls. After removing @Singleton, during concurrent calls, different EntityManager objects are used. If endpoint calls are subsequent, it may be that previous/old EntityManager will be used.

    Highly simplified example:

    @Path("/v1/items")
    public class ItemsService {
    
        @Inject
        private EntityManager entityManager;
    
        @POST
        @Path("/{id}")
        @Consumes(MediaType.APPLICATION_JSON)
        @Produces(MediaType.APPLICATION_JSON)
        public void saveItem(){
             entityManager.getTransaction().begin();
             entityManager.persist(new Item());
             entityManager.getTransaction().commit();
        }
    }
    

提交回复
热议问题