/** Test of an SQL query using a result set mapping giving two entities (Login + LoginAccount). */ public void testSQLResult() { if (vendorID == null) { return; } try { EntityManager em = getEM(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); LoginAccount acct = new LoginAccount(1, "Fred", "Flintstone"); Login login = new Login("flintstone", "pwd"); acct.setLogin(login); em.persist(login); em.persist(acct); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } em = getEM(); tx = em.getTransaction(); try { tx.begin(); // Check the results List result = em.createNativeQuery( "SELECT P.ID, P.FIRSTNAME, P.LASTNAME, P.LOGIN_ID, L.ID, L.USERNAME, L.PASSWORD " + "FROM JPA_AN_LOGINACCOUNT P, JPA_AN_LOGIN L", "AN_LOGIN_PLUS_ACCOUNT") .getResultList(); assertEquals(1, result.size()); Iterator iter = result.iterator(); while (iter.hasNext()) { // Should be a String (type of "ID" column) Object[] obj = (Object[]) iter.next(); assertEquals("Fred", ((LoginAccount) obj[0]).getFirstName()); assertEquals("flintstone", ((Login) obj[1]).getUserName()); assertEquals("Fred", ((LoginAccount) obj[0]).getFirstName()); assertTrue(((LoginAccount) obj[0]).getLogin() == ((Login) obj[1])); } tx.rollback(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } finally { clean(LoginAccount.class); clean(Login.class); } }
/* The annotation @AroundInvoke sign this method for to be called automatically before the method annotated with @Transactional */ @AroundInvoke public Object invoke(InvocationContext context) throws Exception { EntityTransaction entityTransaction = entityManager.getTransaction(); boolean owner = false; try { if (!entityTransaction.isActive()) { // A way to grant any operation pending will be rollback, preventing possible errors. entityTransaction.begin(); entityTransaction.rollback(); // Now, after check about posible errors, the transaction is started. entityTransaction.begin(); owner = true; } // After transaction started, the content of any method intercepted as @Transactional is run. return context.proceed(); } catch (Exception e) { if (entityTransaction != null && owner) { // Any anomaly operation and the changes are undone entityTransaction.rollback(); } throw e; } finally { if (entityTransaction != null && entityTransaction.isActive() && owner) { // Finaly, without any errors, the changes are sended to the database. entityTransaction.commit(); } } }
@AroundInvoke public Object invoke(InvocationContext context) throws Exception { EntityTransaction trx = manager.getTransaction(); boolean criador = false; try { if (!trx.isActive()) { // truque para fazer rollback no que já passou // (senão, um futuro commit, confirmaria até mesmo operações sem transação) trx.begin(); trx.rollback(); // agora sim inicia a transação trx.begin(); criador = true; } return context.proceed(); } catch (Exception e) { if (trx != null && criador) { trx.rollback(); } throw e; } finally { if (trx != null && trx.isActive() && criador) { trx.commit(); } } }
public void queryMedicalHistory4() { EntityManager em = emf.createEntityManager(); Map medicals = new HashMap(); long ssn = 0; EntityTransaction tran = em.getTransaction(); tran.begin(); String jpql = "select m from MedicalHistory2 m"; Query q = em.createQuery(jpql); List<MedicalHistory2> ms = q.getResultList(); for (MedicalHistory2 m : ms) { ssn = m.getId(); } tran.commit(); em.close(); em = emf.createEntityManager(); tran = em.getTransaction(); tran.begin(); jpql = "select m from MedicalHistory2 m where m.patient.ssn = " + ssn; q = em.createQuery(jpql); ms = q.getResultList(); for (MedicalHistory2 m : ms) { assertMedicalHistory2(m); } tran.commit(); em.close(); findObj4(ssn); }
public static void main(String[] args) { // Start EntityManagerFactory EntityManagerFactory emf = Persistence.createEntityManagerFactory("black", new DBConnector().mysql); // First unit of work EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); // Persist data MessageHibModel MessageHib = new MessageHibModel("Hello World with JPA and JTA"); em.persist(MessageHib); // Commit & close tx.commit(); em.close(); // Second unit of work EntityManager newEm = emf.createEntityManager(); EntityTransaction newTx = newEm.getTransaction(); newTx.begin(); MessageHibModel m = new MessageHibModel(); m.setText("Hello World with JPA and JTA"); @SuppressWarnings("unchecked") List<EntityManager> MessageHibs = newEm .createQuery( "select m from MessageHibModel m where m.text like :sText order by m.text asc") .setParameter("sText", m.getText()) .setFlushMode(FlushModeType.COMMIT) // .setHint("org.hibernate.cacheMode",org.hibernate.CacheMode.IGNORE) .setHint("org.hibernate.cacheable", true) .setHint("org.hibernate.readOnly", true) .setHint("org.hibernate.comment", "My Comment...") .setFirstResult(1) // .getSingleResult() .setMaxResults(20) .getResultList(); System.out.println(MessageHibs.size() + " Message(s) found:"); for (Object m1 : MessageHibs) { MessageHibModel loadedMsg = (MessageHibModel) m1; System.out.println(loadedMsg.getText()); } newTx.commit(); newEm.close(); // Shutting down the application emf.close(); }
/** Test of an SQL query persisting the object and querying in a different txn. */ public void testBasic2() { if (vendorID == null) { return; } try { EntityManager em = getEM(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); // Persist an object Person p = new Person(101, "Fred", "Flintstone", "*****@*****.**"); p.setAge(34); em.persist(p); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } em = getEM(); tx = em.getTransaction(); try { tx.begin(); // Check the results List result = em.createNativeQuery("SELECT P.PERSON_ID FROM JPA_AN_PERSON P WHERE P.AGE_COL=34") .getResultList(); assertEquals(1, result.size()); Iterator iter = result.iterator(); while (iter.hasNext()) { // Should be a Long or equivalent (type of "PERSON_ID" column (Person.personNum field)); // Oracle returns BigDecimal Object obj = iter.next(); assertTrue( "SQL query has returned an object of an incorrect type", Number.class.isAssignableFrom(obj.getClass())); } tx.rollback(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } } finally { clean(Person.class); } }
@Override public void delete(Object instance) { EntityTransaction tx = manager.getTransaction(); tx.begin(); manager.remove(instance); tx.commit(); }
public static void main(String[] args) { try { EntityManagerFactory f = Persistence.createEntityManagerFactory("DemoPU"); EntityManager manager = f.createEntityManager(); Scanner in = new Scanner(System.in); System.out.print("Enter id to modify"); int id = in.nextInt(); in.nextLine(); Emp e = manager.find(Emp.class, id); System.out.println("current details are"); System.out.println(e.getEname() + "\t" + e.getJob() + "\t" + e.getSalary()); System.out.println("Enter name to update"); String n = in.nextLine(); System.out.println("Enter job to update"); String j = in.nextLine(); System.out.println("Enter salary to update"); int s = in.nextInt(); EntityTransaction t = manager.getTransaction(); t.begin(); e.setEname(n); e.setJob(j); e.setSalary(s); t.commit(); manager.close(); System.out.println("updated"); } catch (Exception e) { System.out.println(e); } }
public void updateContact(Contact cn, String id) { EntityTransaction et = em.getTransaction(); et.begin(); Query query = em.createQuery("UPDATE c from Contact c WHERE c.id=" + id); query.executeUpdate(); et.commit(); }
private void withBatch() { int entityCount = 100; // tag::batch-session-batch-insert-example[] EntityManager entityManager = null; EntityTransaction txn = null; try { entityManager = entityManagerFactory().createEntityManager(); txn = entityManager.getTransaction(); txn.begin(); int batchSize = 25; for (int i = 0; i < entityCount; ++i) { Person Person = new Person(String.format("Person %d", i)); entityManager.persist(Person); if (i % batchSize == 0) { // flush a batch of inserts and release memory entityManager.flush(); entityManager.clear(); } } txn.commit(); } catch (RuntimeException e) { if (txn != null && txn.isActive()) txn.rollback(); throw e; } finally { if (entityManager != null) { entityManager.close(); } } // end::batch-session-batch-insert-example[] }
// cr�ation d'objets public static void test1() throws ParseException { // contexte de persistance EntityManager em = getEntityManager(); // cr�ation personnes p1 = new Personne( "Martin", "Paul", new SimpleDateFormat("dd/MM/yy").parse("31/01/2000"), true, 2); p2 = new Personne( "Durant", "Sylvie", new SimpleDateFormat("dd/MM/yy").parse("05/07/2001"), false, 0); // cr�ation adresses a1 = new Adresse("8 rue Boileau", null, null, "49000", "Angers", null, "France"); a2 = new Adresse("Apt 100", "Les Mimosas", "15 av Foch", "49002", "Angers", "03", "France"); a3 = new Adresse("x", "x", "x", "x", "x", "x", "x"); a4 = new Adresse("y", "y", "y", "y", "y", "y", "y"); // associations personne <--> adresse p1.setAdresse(a1); p2.setAdresse(a2); // d�but transaction EntityTransaction tx = em.getTransaction(); tx.begin(); // persistance des personnes em.persist(p1); em.persist(p2); // et des adresses a3 et a4 non li�es � des personnes em.persist(a3); em.persist(a4); // fin transaction tx.commit(); // on affiche les tables dumpPersonne(); dumpAdresse(); }
public static void modificarPuesto(int idEmpleado, String Puesto) { EmpleadoEntity empleado = getEmpleadoPorID(idEmpleado); EntityTransaction entityTransaction = ConexionBD.getEm().getTransaction(); entityTransaction.begin(); empleado.setPuesto(Puesto); entityTransaction.commit(); }
private void withoutBatch() { // tag::batch-session-batch-example[] EntityManager entityManager = null; EntityTransaction txn = null; try { entityManager = entityManagerFactory().createEntityManager(); txn = entityManager.getTransaction(); txn.begin(); for (int i = 0; i < 100_000; i++) { Person Person = new Person(String.format("Person %d", i)); entityManager.persist(Person); } txn.commit(); } catch (RuntimeException e) { if (txn != null && txn.isActive()) txn.rollback(); throw e; } finally { if (entityManager != null) { entityManager.close(); } } // end::batch-session-batch-example[] }
public void modificar(Estado c) { EntityManager em = FactoryDAO.em; EntityTransaction etx = em.getTransaction(); etx.begin(); em.merge(c); etx.commit(); }
public InterestRate getInterestRateByInterestRateId(String interestRateId) { // Obtains entity manager object EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager(); // Obtains transaction from entity manager EntityTransaction entr = entityManager.getTransaction(); // -----------Begin transaction----------- InterestRate interestRate = null; try { entr.begin(); // Get a list of accounts from DB TypedQuery<InterestRate> query = entityManager.createQuery( "SELECT i FROM " + InterestRate.class.getName() + " i where i.interestRateId = ?", InterestRate.class); query.setParameter(1, Integer.parseInt(interestRateId)); interestRate = query.getSingleResult(); entr.commit(); } catch (Exception e) { entityManager.close(); } // -----------End transaction----------- return interestRate; }
public static void create(Localidad localidad) { EntityManager entityManager = PersistenceManager.getEntityManager(); EntityTransaction tr = entityManager.getTransaction(); tr.begin(); try { entityManager.persist(localidad); tr.commit(); System.out.println( "Creación de localidad:" + localidad.getNombre() + ", de la prov: " + localidad.getProvincia().getNombre() + " exitosa"); } catch (Exception ex) { tr.rollback(); System.err.println( "Error en LibroDAO.create" + "(" + Thread.currentThread().getStackTrace()[1].getLineNumber() + "):" + ex.getLocalizedMessage()); } finally { entityManager.close(); } }
private static void setUp() { final User user1 = new User("Luca", "Molteni", "lmolteni", "*****@*****.**"); final User user2 = new User("User2", "Surname2", "account2", "*****@*****.**"); final Publisher p1 = new Publisher("All the cool CS books", "San Francisco CA"); final Book b1 = new Book("Java Persistence With Hibernate", 23l, "Gavin King"); final Book b2 = new Book("The C Programming Language ", 30l, "Brian Kerninghan"); p1.addBook(b1); p1.addBook(b2); final Purchase purch1 = new Purchase(user1, b1, 10l); final Purchase purch2 = new Purchase(user1, b2, 20l); final Purchase purch3 = new Purchase(user2, b2, 15l); final EntityManager em = EntityManagerBean.getEntityManager(); final EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(user1); em.persist(user2); em.persist(p1); em.persist(b1); em.persist(b2); em.persist(purch1); em.persist(purch2); em.persist(purch3); tx.commit(); em.close(); }
@Test @RunOrder(5) public void deleteByEntityTest() { getForUpfate(); EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); // ============= Query construction ============== // JpaQueryStream<Person> stream = JpaQueryProvider.delete(em, Person.class) .where() .equal(Person::getPersonalNo, PERSONAL_NO2) .and() .like(Person::getLastName, "lname%") .and() .startsWith(Person::getFirstName, "fname"); int rows = stream.execute(); // =============================================// transaction.commit(); System.out.println(); System.out.println("-------Entity----"); System.out.println(); System.out.format("deleted %s rows\n", rows); Assert.assertEquals("No expected row number was updated", rows, 1); } catch (Throwable ex) { rollback(transaction); } finally { em.close(); } }
private void getForUpfate() { EntityManager em = emf.createEntityManager(); EntityTransaction transaction = em.getTransaction(); try { JpaQueryStream<Person> stream = JpaQueryProvider.select(em, Person.class) .where() .equal(Person::getPersonalNo, PERSONAL_NO2) .and() .like(Person::getLastName, "lname%") .and() .startsWith(Person::getFirstName, "fname"); Person person = stream.getFirst(); transaction.begin(); if (person == null) { Person newPerson = QueryTest.initPerson(); em.persist(newPerson); person = newPerson; } transaction.commit(); } catch (Throwable ex) { rollback(transaction); } finally { em.close(); } }
/** * Update person * * @param p * @return */ public Person updatePerson(Person p) { // Call setters if (p.birthdate != null) { this.setBirthdate(p.birthdate); } if (p.email != null) { this.setEmail(p.email); } if (p.firstname != null) { this.setFirstname(p.getFirstname()); } if (p.lastname != null) { this.setLastname(p.getLastname()); } EntityManager em = LifeStyleDao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); p = em.merge(this); tx.commit(); LifeStyleDao.instance.closeConnections(em); return p; }
/** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); List<entities.Course> courses = new ArrayList<entities.Course>(); if (session.getAttribute("courses_validated_list") == null) { // 1 Create the factory of Entity Manager EntityManagerFactory factory = Persistence.createEntityManagerFactory("PersistenceJPAProject"); // 2 Create the Entity Manager EntityManager em = factory.createEntityManager(); // 3 Get one EntityTransaction and start it EntityTransaction tx = em.getTransaction(); tx.begin(); try { courses = em.createNamedQuery("Course.findValidatedCourses", entities.Course.class) .getResultList(); } catch (NoResultException e) { courses = null; } session.setAttribute("courses_validated_list", courses); tx.commit(); em.close(); } ((HttpServletResponse) response).sendRedirect("CoursesList.jsp"); }
@Override public void beginTransaction() { EntityTransaction transaction = getEntityManager().getTransaction(); if (!transaction.isActive()) { transaction.begin(); } }
public void guardar(Estado c) { EntityManager em = FactoryDAO.em; EntityTransaction etx = em.getTransaction(); etx.begin(); em.persist(c); etx.commit(); }
public static void modificarNombre(int idEmpleado, String nombre) { EmpleadoEntity empleado = getEmpleadoPorID(idEmpleado); EntityTransaction entityTransaction = ConexionBD.getEm().getTransaction(); entityTransaction.begin(); empleado.setNombre(nombre); entityTransaction.commit(); }
public List<InterestRate> getInterestRates() { // Obtains entity manager object EntityManager entityManager = EntityManagerFactoryUtil.createEntityManager(); // Obtains transaction from entity manager EntityTransaction entr = entityManager.getTransaction(); // -----------Begin transaction----------- List<InterestRate> interestRates = null; try { entr.begin(); // Get a list of accounts from DB TypedQuery<InterestRate> query = entityManager.createQuery( "SELECT i FROM " + InterestRate.class.getName() + " i", InterestRate.class); interestRates = query.getResultList(); entr.commit(); } catch (Exception e) { entityManager.close(); } // -----------End transaction----------- return interestRates; }
public static void createTask(EntityManager em) { EntityTransaction entr = em.getTransaction(); entr.begin(); Task t = new Task(); t.setEnable(1); t.setName("ACP_Publisher"); t.setProvider("eu.gloria.rt.worker.offshore.WorkerOffshorePublisher"); t.setSleepTime(1000); em.persist(t); /*ArrayList<TaskProperty> props = new ArrayList<TaskProperty>(); TaskProperty prop = new TaskProperty(); prop.setName("sleepTime"); prop.setValue("5000"); prop.setType(TaskPropertyType.INT); prop.setTask(t); props.add(prop); em.persist(prop);*/ entr.commit(); System.out.println(""); }
/** * Updates or adds an agent to the database. * * @param agent The Agent you wish to modify or add in the database. */ protected void updateAgentInDatabase(AgentImpl agent) { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); AgentImpl existing = getAgent(agent.getName(), agent.getOrganization(), em); if (existing == null) { em.persist(agent); } else { existing.setConfiguration(agent.getConfiguration()); existing.setLastHeardFrom(agent.getLastHeardFrom()); existing.setState(agent.getState()); existing.setSchedulerRoles(agent.getSchedulerRoles()); existing.setUrl(agent.getUrl()); em.merge(existing); } tx.commit(); } catch (RollbackException e) { logger.warn("Unable to commit to DB in updateAgent."); throw e; } finally { if (em != null) em.close(); } }
public boolean estudianteCumplePreRequisitos(Integer id, Integer prerequisitoCursoId) throws NoPrerrequisitosException { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); boolean ret = false; try { tx = em.getTransaction(); tx.begin(); tx.commit(); ret = service.estudianteCumplePreRequisitos(id, prerequisitoCursoId, em); if (ret == false) throw new NoPrerrequisitosException("El estudiante no cumple con los prerequisitos"); } catch (Exception e) { if (em != null && tx != null) { tx.rollback(); } throw new NoPrerrequisitosException("El estudiante no cumple con los prerequisitos"); } finally { if (em != null) { em.clear(); em.close(); } return ret; } }
void markAsBroken(ETask task, EntityManager em) { EntityTransaction et = em.getTransaction(); et.begin(); task.setStatus(ETask.statusSysError); et.commit(); }
/** * Retrieve a task list for the user. Tasks are retrieved from the storage for the user performing * the request. * * @return A list of tasks */ private List<Task> retrieveTaskList() { List<Task> lstTasks = new LinkedList<>(); EntityManager em = getEntityManager(); EntityTransaction et = null; List<Object[]> taskList = null; try { et = em.getTransaction(); et.begin(); taskList = em.createNamedQuery("tasks.userAll").setParameter("user", getUser()).getResultList(); et.commit(); } catch (RuntimeException re) { if (et != null && et.isActive()) { et.rollback(); } log.error("Impossible to retrieve the task list"); log.error(re); throw new RuntimeException("Impossible to access the task list"); } finally { em.close(); } if (taskList != null && !taskList.isEmpty()) { for (Object[] elem : taskList) { int idElem = 0; Task tmpTask = new Task(); tmpTask.setId((String) elem[idElem++]); tmpTask.setDescription((String) elem[idElem++]); tmpTask.setState((Task.STATE) elem[idElem++]); tmpTask.setDateCreated((Date) elem[idElem]); lstTasks.add(tmpTask); } } return lstTasks; }