April 05
Prof. Ismael H. F. Santos -  ismael@tecgraf.puc-rio.br                                                          2
JPA Queries – JPAQL
nExemplo 4 – JPA Query
n
n EntityManagerFactory f = Persistence.
n   createEntityManagerFactory("Tutorial");
n EntityManager e= f.createEntityManager();
n ......
n Transaction tx = em.getTransaction();
n try {
n   tx.begin();
n     Employee emp = new Employee();
n     emp.setName("Miller");
n     emp.setSalary(10000);
n     e.persist(product);
n   tx.commit();
n } finally {
n   if (tx.isActive()) {
n     tx.rollback();
n   }  
n   em.close();
n }
n ......
n tx = em.getTransaction();
n try {
n    tx.begin();
n      Query q = pm.createQuery("SELECT e FROM
n       Employee e WHERE e.salary >= 1000.00");
n      List results = q.getResultList();
n      Iterator iter = results.iterator();
n      while( iter.hasNext() ) {
n        Employee emp = (Employee)iter.next();
n        ... (use the retrieved object)
n     }
n     tx.commit();
n } finally {
n   if (tx.isActive()) {
n     tx.rollback();
n   }  
n   em.close();
n}
n
n// Find and delete all objects whose last name
n// is 'Jones'
nQuery q = e.createQuery("DELETE FROM Person p WHERE p.lastName = 'Jones'");
nint numberInstancesDeleted= q.executeUpdate();