Java Reference
In-Depth Information
Listings A-1 and A-2) containing the appropriate configuration information. From the
EntityManagerFactory class, you can request EntityManager instances that are used to access
the entities. You have probably already spotted that the EJB 3 Persistence class corresponds
roughly to Configuration , that EntityManagerFactory is a dead ringer for SessionFactory , and
that EntityManager is the analog of Session .
The example code in Listing A-3 pushes this point home. The EntityManager instance is
used in a very similar way to the Session class shown throughout this topic (although some of
the method names are slightly different— persist() in this example corresponds to Session 's
save() method).
Listing A-3. Using EJB 3 Persistence in J2SE Code
package com.hibernatebook.advanced;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class Ejb3Example {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
EntityManagerFactory factory =
Persistence.createEntityManagerFactory(" sampleManager ");
EntityManager manager = factory.createEntityManager();
manager.getTransaction().begin();
manager.persist(new Sample("FAQ"));
manager.persist(new Sample("RTFM"));
manager.persist(new Sample("PDQ"));
manager.persist(new Sample("ASAP"));
manager.getTransaction().commit();
Query query = manager.createQuery("from Sample");
manager.getTransaction().begin();
List<Sample> list = (List<Sample>)query.getResultList();
manager.getTransaction().commit();
for(Sample sample : list) {
System.out.println(sample.getContent());
}
Search WWH ::




Custom Search