简体   繁体   中英

Java Hibernate(JPA) queries

what is the right way to make a query with JPA. Here is my way now:

EntityManagerFactory factory = Persistence.createEntityManagerFactory("hellojpa");
        EntityManager em = factory.createEntityManager();
        em.getTransaction().begin();

        //query here

        em.getTransaction().commit();
        em.close();

I just started learning it and I am pretty sure that there will be more intelligent way. Some helper class, maybe?

Thanks.

In my opinion it is the right way, if you use local transactions. Keep in mind that EntityManager is not thread safe.

You will have less boilerplate code in a JavaEE environment, where the application server takes care of EntityManager injection and uses JTA.

@PersistenceContect
EntityManager em;

public void foo() {
// query
}

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