简体   繁体   中英

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. 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. 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.

I think you should inject the entitymanager itself (not the factory), and let the container take care of instantiation and scopes. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM