[英]JPA create entity manager factory for every request?
First of all I am new to JPA and Jax-rs, i am trying to develop a rest service. 首先,我是JPA和Jax-rs的新手,我想开发一种休息服务。 So i have created a resource class and annotated it.
因此,我创建了一个资源类并对其进行了注释。
@Path("/companies")
public class CompanyResource {
private EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
@GET
@Produces({MediaType.APPLICATION_JSON})
public List<Company> getCompanies() {
EntityManager entityManager = entityManagerFactory.createEntityManager();
return new ArrayList<>();
}
@GET
@Path("{companyId}")
@Produces({MediaType.APPLICATION_JSON})
public Company getCompany(@PathParam("companyId") int id) {
return new Company();
}
}
From what i have understood about jax-rs for every client request instance of CompanyResource
will be created, that means every time new EntityManagerFactory
will be created, which i guess is not a good idea, as i just need it to create entity managers, which could be done with only one instance of it. 根据我对
CompanyResource
每个客户端请求实例创建jax-rs的理解,这意味着每次将创建新的EntityManagerFactory
时,我认为这不是一个好主意,因为我只需要它来创建实体管理器,只能用一个实例来完成。 So what is a proper way to achieve this? 那么实现这一目标的正确方法是什么? Or is it ok to create new instance of this factory for every request?
还是可以为每个请求创建该工厂的新实例?
PS i have seen some examples where they use @Stateless
annotation and inject Entity Manager, but i guess they use EJB
there(i might be wrong) and i don't want to deep into EJB
right now. PS我已经看到了一些使用
@Stateless
注释并注入Entity Manager的示例,但是我想他们在那里使用了EJB
(我可能是错的),并且我现在不想深入到EJB
。
I think you should inject the entitymanager itself (not the factory), and let the container take care of instantiation and scopes. 我认为您应该注入entitymanager本身(而不是工厂),并让容器负责实例化和作用域。 What we usually do is something like
我们通常要做的是
@Stateless
@Path("services")
public class MyServices {
@PersistenceContext
private EntityManager em;
// ...
apart from the @Stateless
(which imho you should use, there's no need to get deep into EJB for this), it's actually quite simple. 除了
@Stateless
(您应该使用哪一个恕我直言,无需为此而深入了解EJB),它实际上非常简单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.