/** * 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; }
// DELETANDO OBJETOS public void delete(E obj) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); Integer id = null; try { try { Method getId = obj.getClass().getDeclaredMethod("getId"); id = (Integer) getId.invoke(obj); } catch (Exception ex) { Logger.getLogger(DAO.class.getName()).log(Level.SEVERE, null, ex); } tx.begin(); E removeObj = (E) em.find(obj.getClass(), id); // if (!em.contains(obj)) { // obj = em.merge(obj); // } em.remove(removeObj); tx.commit(); // System.out.println(""); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
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(); }
public List<E> getObjectFromNamedQuery(String namedQuery, Object... parametros) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); int position = 1; List<E> array = new ArrayList<E>(); try { tx.begin(); Query q = em.createNamedQuery(namedQuery); for (Object parametro : parametros) { q.setParameter(position++, parametro); } tx.commit(); array = q.getResultList(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } return array; }
/** * Deletes a Person from the database. * * @param person The person that will be deleted. */ public static void deletePerson(Person person) { EntityManager em = Assignment3Dao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); person = em.merge(person); em.remove(person); tx.commit(); Assignment3Dao.instance.closeConnections(em); }
public static MeasureDefinition saveMeasureDefinition(MeasureDefinition p) { EntityManager em = LifeCoachDao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(p); tx.commit(); LifeCoachDao.instance.closeConnections(em); return p; }
/** * Creates a person in the database. * * @param person The person to be persisted in the database * @return The saved person */ public static Person createPerson(Person person) { EntityManager em = Assignment3Dao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(person); tx.commit(); Assignment3Dao.instance.closeConnections(em); return person; }
/** * Delete person * * @param p */ public static void deletePerson(Person p) { EntityManager em = LifeStyleDao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); p = em.merge(p); em.remove(p); tx.commit(); LifeStyleDao.instance.closeConnections(em); }
public static void removeMeasureDefinition(MeasureDefinition p) { EntityManager em = LifeCoachDao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); p = em.merge(p); em.remove(p); tx.commit(); LifeCoachDao.instance.closeConnections(em); }
public void salvar(Produto produto) { EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.merge(produto); tx.commit(); } catch (Exception e) { tx.rollback(); } }
public List<Contact> getAll() { // ClientRequestContext EntityTransaction et = em.getTransaction(); et.begin(); Query query = em.createQuery("SELECT c from Contact c"); List<Contact> contacts = null; // contacts = em.getResultList(); et.commit(); return contacts; }
/** * Updates a Person in the database. It makes sure to NOT override any data that is not being * updated. * * @param oldPerson The person with the currently saved data. * @param updatedPerson The person with the updated data that will be saved. * @return The updated person */ public static Person updatePerson(Person oldPerson, Person updatedPerson) { updatedPerson = syncPerson(oldPerson, updatedPerson); EntityManager em = Assignment3Dao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); updatedPerson = em.merge(updatedPerson); tx.commit(); Assignment3Dao.instance.closeConnections(em); return updatedPerson; }
public void Delete(Produto obj) throws Exception { try { transaction = manager.getTransaction(); transaction.begin(); manager.remove(obj); transaction.commit(); } catch (Exception ex) { transaction.rollback(); throw ex; } }
public void excluir(Produto produto) { // EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.remove(produto); tx.commit(); } catch (Exception e) { tx.rollback(); e.printStackTrace(); } }
// PESQUISANDO OBJETOS public E findById(Integer id) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); return em.find(clazz, id); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
// INSERINDO OBJETOS public void insertSimpleObject(E obj) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.merge(obj); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
// ATTACH E DETTACH public E attach(E obj) { renewEmAttach(); txAttach = emAttach.getTransaction(); txAttach.begin(); return emAttach.merge(obj); }
/** * Save new person * * @param p * @return */ public static Person savePerson(Person p) { if (p.healthProfile != null) { // Cascade health profile and add to history Person.cascadeHealthProfile(p); Person.copyHealthProfileToHistory(p); } EntityManager em = LifeStyleDao.instance.createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); em.persist(p); tx.commit(); LifeStyleDao.instance.closeConnections(em); return p; }
/** * Actualiza una instancia en la tabla de mecenazgos. * * @param pmecenazgo: Objeto Mecenazgo. */ public static void actualizar(Mecenazgo pmecenazgo) { EntityManager em = JpaUtil.getEntityManagerFactory().createEntityManager(); EntityTransaction tx = em.getTransaction(); tx.begin(); try { em.merge(pmecenazgo); tx.commit(); System.out.println("Actualizacion exitosa"); } catch (Exception ex) { tx.rollback(); System.out.println("Error"); ex.printStackTrace(); } finally { em.close(); } }
@Override public <E> EntityProxy<E> proxyOf(E entity, boolean forUpdate) { checkClosed(); @SuppressWarnings("unchecked") Type<E> type = (Type<E>) entityModel.typeOf(entity.getClass()); EntityProxy<E> proxy = type.getProxyProvider().apply(entity); if (forUpdate && type.isReadOnly()) { throw new ReadOnlyException(); } if (forUpdate) { EntityTransaction transaction = transactionProvider.get(); if (transaction != null && transaction.active()) { transaction.addToTransaction(proxy); } } return proxy; }
// ATUALIZANDO OBJETOS public E update(E obj) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); E e = null; try { tx.begin(); e = em.merge(obj); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } return e; }
public void insertListOfObject(List<E> objList) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); for (E object : objList) { em.persist(object); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
public void insertVariableObjects(E... objetos) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); for (E object : objetos) { em.merge(object); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } }
public List<E> findAll() { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); List<E> list = new ArrayList<E>(); try { tx.begin(); Query q = em.createNamedQuery(clazz.getSimpleName() + ".findAll"); list = q.getResultList(); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); } return list; }
protected void transactional(Consumer<EntityManager> consumer) { EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); boolean success = false; try { tx.begin(); consumer.accept(em); success = true; } finally { try { if (success) { tx.commit(); } else { tx.rollback(); } } finally { em.close(); } } }
// EXECUTANDO QUERIES public Integer executeQuery(String query, Object... parametros) { EntityManager em = getEntityManager(); EntityTransaction tx = em.getTransaction(); int num = 0, position = 1; try { tx.begin(); Query q = em.createQuery(query); for (Object parametro : parametros) { q.setParameter(position++, parametro); } num = q.executeUpdate(); tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } em.close(); return num; } }
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(); }
/** * Run a block of code in a JPA transaction. * * @param name The persistence unit name * @param readOnly Is the transaction read-only? * @param block Block of code to execute */ public <T> T withTransaction(String name, boolean readOnly, Supplier<T> block) { EntityManager entityManager = null; EntityTransaction tx = null; try { entityManager = em(name); if (entityManager == null) { throw new RuntimeException("No JPA entity manager defined for '" + name + "'"); } JPA.bindForSync(entityManager); if (!readOnly) { tx = entityManager.getTransaction(); tx.begin(); } T result = block.get(); if (tx != null) { if (tx.getRollbackOnly()) { tx.rollback(); } else { tx.commit(); } } return result; } catch (Throwable t) { if (tx != null) { try { tx.rollback(); } catch (Throwable e) { } } throw t; } finally { JPA.bindForSync(null); if (entityManager != null) { entityManager.close(); } } }
/** * Run a block of asynchronous code in a JPA transaction. * * @param name The persistence unit name * @param readOnly Is the transaction read-only? * @param block Block of code to execute. * @deprecated This may cause deadlocks */ @Deprecated public <T> F.Promise<T> withTransactionAsync( String name, boolean readOnly, Supplier<F.Promise<T>> block) { EntityManager entityManager = null; EntityTransaction tx = null; try { entityManager = em(name); if (entityManager == null) { throw new RuntimeException("No JPA entity manager defined for '" + name + "'"); } JPA.bindForAsync(entityManager); if (!readOnly) { tx = entityManager.getTransaction(); tx.begin(); } F.Promise<T> result = block.get(); final EntityManager fem = entityManager; final EntityTransaction ftx = tx; F.Promise<T> committedResult = (ftx == null) ? result : result.map( t -> { if (ftx.getRollbackOnly()) { ftx.rollback(); } else { ftx.commit(); } return t; }); committedResult.onFailure( t -> { if (ftx != null) { try { if (ftx.isActive()) { ftx.rollback(); } } catch (Throwable e) { } } try { fem.close(); } finally { JPA.bindForAsync(null); } }); committedResult.onRedeem( t -> { try { fem.close(); } finally { JPA.bindForAsync(null); } }); return committedResult; } catch (Throwable t) { if (tx != null) { try { tx.rollback(); } catch (Throwable e) { } } if (entityManager != null) { try { entityManager.close(); } finally { JPA.bindForAsync(null); } } throw t; } }