List of usage examples for javax.persistence EntityManager getTransaction
public EntityTransaction getTransaction();
EntityTransaction
object. From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
/** * {@inheritDoc}/* w w w. j a v a 2s .c om*/ */ @Override public <T extends BaseEntity> void delete(Class<T> entity, Object primaryKey) { EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory()); try { em.getTransaction().begin(); T entityToDelete = em.find(entity, primaryKey); if (entityToDelete == null) { LOGGER.warn("Entity couldn't be deleted as it doesn't exists in DB: [{}]", entity); } else { em.remove(entityToDelete); em.getTransaction().commit(); } } catch (Exception ex) { // NOSONAR Transactions.markRollback(em); throw new JpaException(ex); } finally { Transactions.rollback(em); JpaUtil.closeEntityManager(em); } }
From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
@Override public <T extends BaseEntity> void batchInsert(List<T> entities, int batchSize) { Validate.isTrue(entities != null && !entities.isEmpty() && batchSize > 1, "Invalid inputs!!"); EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory()); try {/*from www .j av a 2 s.c o m*/ em.getTransaction().begin(); for (int index = 0; index < entities.size(); index++) { if (index > 0 && index % batchSize == 0) { em.getTransaction().commit(); em.getTransaction().begin(); em.clear(); } em.persist(entities.get(index)); } em.getTransaction().commit(); } catch (Exception ex) { // NOSONAR Transactions.markRollback(em); throw new JpaException(ex); } finally { Transactions.rollback(em); JpaUtil.closeEntityManager(em); } }
From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
/** * {@inheritDoc}//from w ww . j a v a 2 s.c om */ @Override public <T extends BaseEntity> int deleteByCriteria(DeleteCriteria<T> criteria) { EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory()); try { em.getTransaction().begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaDelete<T> cd = cb.createCriteriaDelete(criteria.getEntity()); Root<T> root = cd.from(criteria.getEntity()); int rowsDeleted = em .createQuery(cd.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root)))) .executeUpdate(); em.getTransaction().commit(); LOGGER.debug("deleteByCriteria: No. of rows deleted: [{}]", rowsDeleted); return rowsDeleted; } catch (Exception ex) { // NOSONAR Transactions.markRollback(em); throw new JpaException(ex); } finally { Transactions.rollback(em); JpaUtil.closeEntityManager(em); } }
From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java
/** * {@inheritDoc}/*from w ww . ja v a 2 s . c om*/ */ @Override public <T extends BaseEntity> int updateByCriteria(UpdateCriteria<T> criteria) { EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory()); try { em.getTransaction().begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaUpdate<T> cu = cb.createCriteriaUpdate(criteria.getEntity()); criteria.getUpdateAttributes().forEach(cu::set); Root<T> root = cu.from(criteria.getEntity()); int rowsUpdated = em .createQuery(cu.where(cb.and(Predicates.from(criteria.getCriteriaAttributes(), cb, root)))) .executeUpdate(); em.getTransaction().commit(); LOGGER.debug("No. of rows updated: {}", rowsUpdated); return rowsUpdated; } catch (Exception ex) { // NOSONAR Transactions.markRollback(em); throw new JpaException(ex); } finally { Transactions.rollback(em); JpaUtil.closeEntityManager(em); } }
From source file:com.jada.admin.customAttribute.CustomAttributeGroupMaintAction.java
public ActionForward remove(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Throwable { Site site = getAdminBean(request).getSite(); EntityManager em = JpaConnection.getInstance().getCurrentEntityManager(); CustomAttributeGroupMaintActionForm form = (CustomAttributeGroupMaintActionForm) actionForm; try {//w w w .j a va2s . com CustomAttributeGroup customAttributeGroup = CustomAttributeGroupDAO.load(site.getSiteId(), Format.getLong(form.getCustomAttribGroupId())); em.remove(customAttributeGroup); em.getTransaction().commit(); } catch (Exception e) { if (Utility.isConstraintViolation(e)) { ActionMessages errors = new ActionMessages(); errors.add("error", new ActionMessage("error.remove.customAttributeGroup.constraint")); saveMessages(request, errors); return actionMapping.findForward("error"); } throw e; } ActionForward actionForward = actionMapping.findForward("removeSuccess"); return actionForward; }
From source file:com.sun.socialsite.userapi.UserManagerImpl.java
private UserRole getOrCreateRole(String roleName) throws PersistenceException { UserRole role = null;//www. ja va 2s .c o m try { Query query = getNamedQuery("UserRole.findByRoleName"); query.setParameter("roleName", roleName); role = (UserRole) query.getSingleResult(); } catch (NoResultException nre) { // create the role in database EntityManager em2 = null; try { em2 = getEmf().createEntityManager(); em2.getTransaction().begin(); UserRole newRole = new UserRole(); newRole.setRoleName(roleName); em2.persist(newRole); em2.flush(); em2.getTransaction().commit(); } catch (PersistenceException pe) { if (em2 == null) { // If we couldn't even create an EntityManager, something is clearly wrong throw pe; } else { // Otherwise, ignore exception for now; the role may have been created in another thread if (em2.getTransaction().isActive()) em2.getTransaction().rollback(); } } finally { if (em2 != null) em2.close(); } } // If role is null, try again (since it _should_ now exist in the DB). if (role == null) { Query query = getNamedQuery("UserRole.findByRoleName"); query.setParameter("roleName", roleName); role = (UserRole) query.getSingleResult(); } return role; }
From source file:info.dolezel.jarss.rest.v1.FeedsService.java
@POST @Path("{id}/markAllRead") public Response markAllRead(@Context SecurityContext context, @PathParam("id") int feedId, @QueryParam("allBefore") long timeMillis) { EntityManager em; EntityTransaction tx;/*from w ww. ja v a2s . c om*/ User user; Feed feed; Date newDate; user = (User) context.getUserPrincipal(); em = HibernateUtil.getEntityManager(); tx = em.getTransaction(); tx.begin(); try { feed = em.find(Feed.class, feedId); if (feed == null) { return Response.status(Response.Status.NOT_FOUND) .entity(new ErrorDescription("Feed does not exist")).build(); } if (!feed.getUser().equals(user)) { return Response.status(Response.Status.FORBIDDEN) .entity(new ErrorDescription("Feed not owned by user")).build(); } newDate = new Date(timeMillis); if (feed.getReadAllBefore() == null || feed.getReadAllBefore().before(newDate)) { feed.setReadAllBefore(newDate); em.persist(feed); } em.createQuery( "delete from FeedItem fi where fi.feed = :feed and fi.data.date < :date and not fi.starred and not fi.exported and size(fi.tags) = 0") .setParameter("feed", feed).setParameter("date", newDate).executeUpdate(); tx.commit(); return Response.noContent().build(); } finally { if (tx.isActive()) tx.rollback(); em.close(); } }
From source file:com.thruzero.domain.jpa.transaction.JpaDatabaseTransactionMgr.java
protected EntityManager doGetCurrentPersistenceManager(boolean autoCreateTransaction) { JpaTransactionState txState = localTransactionState.get(); EntityManager currentEntityManager = txState.getEntityManager(); if (autoCreateTransaction && !isTransactionActive()) { if (currentEntityManager != null && currentEntityManager.isOpen()) { transactionMgrLogHelper.logEntityManagerNotClosedWarning(); currentEntityManager.close(); }// www . j a v a2 s . c o m // begins a transaction if not currently active currentEntityManager = createEntityManager(); if (!isTransactionActive()) { currentEntityManager.getTransaction().begin(); } txState.setEntityManager(currentEntityManager); } return currentEntityManager; }
From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java
private boolean unregister(DzRegPK registryKey, Timestamp today) { EntityManager em = null; PersistentServiceFactory psf = null; try {/*from www . ja v a 2 s . co m*/ psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU); em = psf.getEntityManager(); em.getTransaction().begin(); DzReg r = em.find(DzReg.class, registryKey); r.setActive(_INACTIVE); r.setInsertedDt(today); em.getTransaction().commit(); return true; } catch (javax.persistence.NoResultException nre) { em.getTransaction().rollback(); log.error(registryKey + " not found!"); return false; } catch (Exception ex) { em.getTransaction().rollback(); return false; } finally { em.close(); } }
From source file:BO.UserHandler.java
public boolean login(VUser u) { EntityManager em; EntityManagerFactory emf;//ww w . j av a2 s . com emf = Persistence.createEntityManagerFactory(PERSISTENCE_NAME); em = emf.createEntityManager(); try { Query q = em.createQuery("SELECT u FROM User u WHERE u.email LIKE :email"); q.setParameter("email", u.getEmail()); q.setMaxResults(1); q.getSingleResult(); return true; } catch (NoResultException e) { em.getTransaction().begin(); User userToInsert = new User(u.getEmail()); em.persist(userToInsert); em.flush(); em.getTransaction().commit(); return true; } finally { if (em != null) { em.close(); } emf.close(); } }