List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:de.iai.ilcd.model.dao.AbstractDao.java
/** * Default persist/* w ww . j a va 2 s. com*/ * * @param objs * objects to persist * @throws PersistException * on errors (transaction is being rolled back) */ public void persist(Collection<T> objs) throws PersistException { if (objs == null || objs.isEmpty()) { return; } EntityManager em = PersistenceUtil.getEntityManager(); EntityTransaction t = em.getTransaction(); try { t.begin(); for (T obj : objs) { em.persist(obj); } t.commit(); } catch (Exception e) { t.rollback(); throw new PersistException(e.getMessage(), e); } }
From source file:de.iai.ilcd.model.dao.AbstractDao.java
/** * Default remove: bring back to persistence context if required and delete * //from www . j av a2 s . c o m * @param obj * object to remove * @return remove object * @throws Exception * on errors (transaction is being rolled back) */ public T remove(T obj) throws Exception { if (obj == null) { return null; } EntityManager em = PersistenceUtil.getEntityManager(); EntityTransaction t = em.getTransaction(); try { t.begin(); T tmp = em.contains(obj) ? obj : em.merge(obj); em.remove(tmp); t.commit(); return tmp; } catch (Exception e) { t.rollback(); throw e; } }
From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java
@Override public List<VacancySkill> getSkills(Vacancy vacancy) { EntityManager em = entityManagerFactory.createEntityManager(); List<VacancySkill> list = new LinkedList<>(); try {/*from ww w .j a v a 2 s .com*/ em.getTransaction().begin(); TypedQuery<VacancySkill> query = em.createNamedQuery("VacancySkill.findByVacancy", VacancySkill.class); query.setParameter("vacancy", vacancy); list = query.getResultList(); em.getTransaction().commit(); } catch (RuntimeException e) { Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e); } finally { if (em.getTransaction().isActive()) { em.getTransaction().rollback(); } em.close(); } return list; }
From source file:de.iai.ilcd.model.dao.AbstractDao.java
/** * Default merge//from w ww. j av a2s . com * * @param objs * objects to merge * @return list of merged/managed objects * @throws MergeException * on errors (transaction is being rolled back) */ public Collection<T> merge(Collection<T> objs) throws MergeException { if (objs == null || objs.isEmpty()) { return null; } final Collection<T> tmp = new ArrayList<T>(); EntityManager em = PersistenceUtil.getEntityManager(); EntityTransaction t = em.getTransaction(); try { t.begin(); for (T obj : objs) { tmp.add(em.merge(obj)); } t.commit(); return tmp; } catch (Exception e) { t.rollback(); throw new MergeException("Cannot merge changes to " + String.valueOf(objs) + " into the database", e); } }
From source file:de.iai.ilcd.model.dao.AbstractDao.java
/** * Default remove: bring back to persistence context if required and delete * //w ww . java 2 s .co m * @param objs * objects to remove * @return removed objects * @throws Exception * on errors (transaction is being rolled back) */ public Collection<T> remove(Collection<T> objs) throws Exception { if (objs == null || objs.isEmpty()) { return null; } Collection<T> res = new ArrayList<T>(); EntityManager em = PersistenceUtil.getEntityManager(); EntityTransaction t = em.getTransaction(); try { t.begin(); for (T obj : objs) { T tmp = em.contains(obj) ? obj : em.merge(obj); em.remove(tmp); res.add(tmp); } t.commit(); return res; } catch (Exception e) { t.rollback(); throw e; } }
From source file:com.github.jinahya.persistence.ShadowTest.java
@Test(enabled = false, invocationCount = 1) public void testNassword() { final EntityManager manager = LocalPU.createEntityManager(); try {//from www.j av a2 s. c o m final EntityTransaction transaction = manager.getTransaction(); transaction.begin(); try { final String username = newUsername(manager); byte[] password = newPassword(); Shadow shadow = persistInstance(manager, username, password); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); for (int i = 0; i < 3; i++) { System.out.println("-------------------------------------"); Assert.assertTrue(shadow.puthenticate(shadow, password)); final byte[] nassword = newPassword(); shadow.nassword(shadow, password, nassword); shadow = manager.merge(shadow); manager.flush(); LOGGER.log(Level.INFO, "morton.list: {0}", MORTONS(manager, 0, 1024)); Assert.assertFalse(shadow.puthenticate(shadow, password)); Assert.assertTrue(shadow.puthenticate(shadow, nassword)); password = nassword; } transaction.commit(); } catch (Exception e) { LocalPU.printConstraintViolation(e); transaction.rollback(); e.printStackTrace(System.err); Assert.fail(e.getMessage()); } } finally { manager.close(); } }
From source file:kirchnerei.note.model.DataService.java
public Long storeNote(NoteData noteData) { EntityManager em = null; EntityTransaction tx = null;/*ww w .j a v a2 s .com*/ try { em = entityService.get(); tx = em.getTransaction(); tx.begin(); // search for category String category = noteData.getCategory(); if (StringUtils.isEmpty(category)) { LogUtils.warn(log, "note without category is not allow [%s]", noteData); return null; } TypedQuery<Category> q = em.createNamedQuery("findCategory", Category.class); q.setParameter("category", category); Category cat = getSingleResult(q); if (cat == null) { // a new category cat = new Category(); cat.setTitle(category); em.persist(cat); } final Note note; if (NumberUtils.isEmpty(noteData.getId())) { // create a new note note = beanCopy.copy(noteData, Note.class, noteProperties); note.setCategory(cat); cat.getNotes().add(note); } else { // update an existed note note = em.find(Note.class, noteData.getId()); beanCopy.copy(noteData, note, noteProperties); if (!NumberUtils.compare(note.getCategory().getId(), cat.getId())) { // move to other category note.getCategory().getNotes().remove(note); cat.getNotes().add(note); note.setCategory(cat); } } EntityService.commit(tx); return note.getId(); } catch (Exception e) { EntityService.rollback(tx); return null; } finally { EntityService.close(em); } }
From source file:it.infn.ct.futuregateway.apiserver.v1.InfrastructureService.java
/** * Removes the infrastructure. Delete the infrastructure only if there are * not applications associated with it to avoid inconsistency in the DB. * <p>/*from ww w . ja v a2s. c o m*/ * Infrastructures with associated applications can only be disabled to * avoid future execution of applications. * * @param id Id of the infrastructure to remove */ @DELETE public final void deleteInfra(@PathParam("id") final String id) { Infrastructure infra; EntityManager em = getEntityManager(); try { infra = em.find(Infrastructure.class, id); if (infra == null) { throw new NotFoundException(); } EntityTransaction et = em.getTransaction(); try { et.begin(); List<Object[]> appsForInfra = em.createNamedQuery("applications.forInfrastructure") .setParameter("infraId", id).setMaxResults(1).getResultList(); if (appsForInfra == null || appsForInfra.isEmpty()) { em.remove(infra); } else { throw new WebApplicationException("The infrastructure " + "cannot be removed because there are associated " + "applications", Response.Status.CONFLICT); } et.commit(); } catch (WebApplicationException wex) { throw wex; } catch (RuntimeException re) { log.error(re); log.error("Impossible to remove the infrastructure"); throw new InternalServerErrorException("Errore to remove " + "the infrastructure " + id); } finally { if (et != null && et.isActive()) { et.rollback(); } } } catch (IllegalArgumentException re) { log.error("Impossible to retrieve the infrastructure list"); log.error(re); throw new BadRequestException("Task '" + id + "' does not exist!"); } finally { em.close(); } }
From source file:it.infn.ct.futuregateway.apiserver.v1.ApplicationService.java
/** * Removes the application. Delete the application only if there are not * tasks associated with it because tasks must be associated with an * application.// ww w .j a v a 2 s.com * <p> * Applications with associated tasks can only be disabled to avoid future * execution of new tasks. Nevertheless, a task can be associated with a * disabled application and in this case will stay waiting until the * application is enabled. * * @param id Id of the application to remove */ @DELETE public final void deleteApp(@PathParam("id") final String id) { Application app; EntityManager em = getEntityManager(); try { app = em.find(Application.class, id); if (app == null) { throw new NotFoundException(); } EntityTransaction et = em.getTransaction(); try { et.begin(); List<Object[]> taskForApp = em.createNamedQuery("tasks.forApplication").setParameter("appId", id) .setMaxResults(1).getResultList(); if (taskForApp == null || taskForApp.isEmpty()) { em.remove(app); } else { log.info("Application " + id + " has tasks and cannot be" + " deleted"); throw new WebApplicationException( "The application cannot " + "be removed because there are associated tasks", Response.Status.CONFLICT); } et.commit(); } catch (WebApplicationException wex) { throw wex; } catch (RuntimeException re) { log.error(re); log.error("Impossible to remove the application"); throw new InternalServerErrorException("Error to remove " + "the application " + id); } finally { if (et != null && et.isActive()) { et.rollback(); } } } catch (IllegalArgumentException re) { log.error("Impossible to retrieve the application list"); log.error(re); throw new BadRequestException("Application '" + id + "' " + "does not exist!"); } finally { em.close(); } }
From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java
/** * Deletes a news article from the db/*w w w .jav a 2 s. co m*/ * * @param entity The article to delete */ public void delete(UXBEntity entity) throws Exception { EntityManager em = null; EntityTransaction tx = null; try { em = emf.createEntityManager(); tx = em.getTransaction(); tx.begin(); // Query query = em.createQuery(new StringBuilder().append("SELECT x FROM Article x WHERE x.aid = ").append(entity.getUuid()).append(" AND x.language='").append(entity.getLanguage()).append("'").toString()); Query query = em.createQuery(new StringBuilder() .append("SELECT x FROM article x WHERE x.aid = :fsid AND x.language=:language").toString()); query.setParameter("fsid", Long.parseLong(entity.getUuid())); query.setParameter("language", entity.getLanguage()); if (!query.getResultList().isEmpty()) { Article art = (Article) query.getSingleResult(); em.remove(art); } tx.commit(); } catch (Exception e) { if (tx != null) { tx.setRollbackOnly(); throw e; } logger.error("Failure while deleting from the database", e); } finally { if (tx != null && tx.isActive()) { if (tx.getRollbackOnly()) { tx.rollback(); } } if (em != null) { em.close(); } } }