// one entity manager factory, thread safe
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("PERSISTENCE1");
// get the entity manager for database operation
EntityManager em = factory.createEntityManager();
// get the session for database operation
Session session = em.unwrap(Session.class);
em.getTransaction().begin();
em.getTransaction().rollback();
// flush to database for persistence
em.persist(o);
// release resources
emf.close();
em.close();
Get the EntityManager
// one entity manager factory, thread safe
EntityManagerFactory factory =
Persistence.createEntityManagerFactory("PERSISTENCE1");
// get the entity manager for database operation
EntityManager em = factory.createEntityManager();
Save entity
// flush to database for persistence
em.persist(o);
Example
Employee employee = new Employee();
employee.setFirstName(fName);
employee.setLastName(lName);
em.persist(employee)
Find entity
Find by primary key
em.find(Bar.class, primaryKey);
More complicated looking
The EntityManager.createQuery
and EntityManager.createNamedQuery
methods are used to query the datastore by using Java Persistence query language queries.
public List<DepartmentEntity> getAllDepartments()
{
List<DepartmentEntity> depts = manager.createQuery("Select a From DepartmentEntity a",
DepartmentEntity.class).getResultList();
return depts;
}
public List findWithName(String name) {
return em.createQuery(
"SELECT c FROM Customer c WHERE c.name LIKE :custName")
.setParameter("custName", name)
.setMaxResults(10)
.getResultList();
}
@NamedQuery(
name="findAllCustomersWithName",
query="SELECT c FROM Customer c WHERE c.name LIKE :custName"
)
@PersistenceContext
public EntityManager em;
customers = em.createNamedQuery("findAllCustomersWithName")
.setParameter("custName", "Smith")
.getResultList();