Example usage for javax.persistence EntityManager getTransaction

List of usage examples for javax.persistence EntityManager getTransaction

Introduction

In this page you can find the example usage for javax.persistence EntityManager getTransaction.

Prototype

public EntityTransaction getTransaction();

Source Link

Document

Return the resource-level EntityTransaction object.

Usage

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Deletes every article older than the creationTime of the UXBEntity
 *
 * @param entity Entity containing the expireDate (= createTime of the entity)
 *//*from ww w  .  ja  v  a 2 s.  c  om*/
public void cleanup(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.lastmodified<:expiredate ").toString());
        query.setParameter("expiredate", entity.getCreateTime());

        if (!query.getResultList().isEmpty()) {
            for (Object obj : query.getResultList()) {
                Article art = (Article) obj;
                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();
        }
    }

}

From source file:info.dolezel.jarss.rest.v1.ws.UnreadNotificationEndpoint.java

@OnWebSocketMessage
public void onMessage(Session session, String text) {
    EntityManager em = null;
    EntityTransaction tx = null;//from  ww  w  . ja va  2  s .com
    try {
        JsonReader reader;
        JsonObject object;
        Token token;

        em = HibernateUtil.getEntityManager();
        tx = em.getTransaction();

        tx.begin();

        reader = Json.createReader(new StringReader(text));
        object = reader.readObject();

        token = Token.loadToken(em, object.getString("token"));
        if (token == null) {
            tx.rollback();

            Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.WARNING,
                    "Invalid token provided over WebSocket");
            session.close();
        } else {
            synchronized (sessions) {
                sessions.put(session, token.getUser());
            }
            synchronized (userSessions) {
                userSessions.put(token.getUser(), session);
            }
        }

        tx.commit();
    } catch (Exception ex) {
        if (tx != null)
            tx.rollback();

        Logger.getLogger(UnreadNotificationEndpoint.class.getName()).log(Level.SEVERE,
                "Error processing incoming WebSocket message", ex);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java

@Override
public boolean delete(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    Vacancy managedVacancy = null;//from ww  w .j av  a2  s  .  c  o m
    try {
        em.getTransaction().begin();
        managedVacancy = em.merge(vacancy);
        em.remove(managedVacancy);
        em.getTransaction().commit();

        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:com.doculibre.constellio.wicket.panels.admin.user.AddEditUserPanel.java

@Override
protected void onSave(AjaxRequestTarget target) {
    ConstellioUser user = userModel.getObject();
    if (password.getModelObject() != null) {
        user.setPassword((String) password.getModelObject());
    }/*from  w  w w  .j  a  v a 2  s  . c  o  m*/

    UserServices userServices = ConstellioSpringUtils.getUserServices();
    RecordCollectionServices collectionServices = ConstellioSpringUtils.getRecordCollectionServices();
    for (EntityModel<UserCredentials> userCredentialsModel : userCredentialsModelMap.values()) {
        UserCredentials userCredentials = userCredentialsModel.getObject();
        if (userCredentials.getId() == null) {
            user.addUserCredentials(userCredentials);

            for (Long credentialGroupId : userCredentialsModelMap.keySet()) {
                CredentialGroup userCredentialsGroup = null;
                for (RecordCollection collection : collectionServices.list()) {
                    for (CredentialGroup credentialGroup : collection.getCredentialGroups()) {
                        if (credentialGroup.getId().equals(credentialGroupId)) {
                            userCredentialsGroup = credentialGroup;
                            break;
                        }
                    }
                }
                userCredentials.setCredentialGroup(userCredentialsGroup);
            }
        }
    }

    EntityManager entityManager = ConstellioPersistenceContext.getCurrentEntityManager();
    if (!entityManager.getTransaction().isActive()) {
        entityManager.getTransaction().begin();
    }
    userServices.makePersistent(user);
    entityManager.getTransaction().commit();
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.EmployeeRepositoryImplementation.java

@Override
public List<Vacancy> getAvailableActiveVacancies(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Integer> list = null;
    List<Vacancy> list1 = null;

    try {//  w  w w.  j a va 2  s  . c o m
        em.getTransaction().begin();

        Query query = em.createNativeQuery(
                "select \"ide\" from (select \"UserSkill\".\"employeeId\", \"UserSkill\".\"experience\", \"VacancySkill\".\"vacancyId\" as \"ide\", \"VacancySkill\".\"experience\",  \"UserSkill\".\"allSkillsId\" from \"UserSkill\" join \"VacancySkill\" on \"UserSkill\".\"allSkillsId\" = \"VacancySkill\".\"allSkillsId\" where \"UserSkill\".\"employeeId\" = ? and \"UserSkill\".\"experience\" >= \"VacancySkill\".\"experience\") group by \"employeeId\", \"ide\" having count(\"employeeId\") >= (select count(*) from \"VacancySkill\" where \"VacancySkill\".\"vacancyId\" = \"ide\")");
        query.setParameter(1, employee.getEmployeeUserId());
        list = query.getResultList();
        if (list.isEmpty()) {
            list.add(0);
        }

        TypedQuery<Vacancy> query1 = em.createNamedQuery("Vacancy.findActiveVacanciesByIds", Vacancy.class);
        query1.setParameter("vacancyIdList", list);
        list1 = query1.getResultList();

        em.getTransaction().commit();
    } catch (RuntimeException e) {
        Logger.getLogger(EmployeeRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        em.close();
    }

    return list1;
}

From source file:cz.fi.muni.pa165.dto.BookDAOTest.java

@Test
public void testUpdate() {
    EntityManager em = emf.createEntityManager();
    BookDAOImpl bdao = new BookDAOImpl();
    bdao.setManager(em);//from  ww w.j  a  va 2s  .  c  o  m
    Book book = new Book();
    book = em.createQuery("SELECT b FROM Book b", Book.class).getSingleResult();
    em.getTransaction().begin();
    book.setName("Updated!");
    bdao.update(book);
    em.getTransaction().commit();

    Book book2 = em.createQuery("SELECT b FROM Book b", Book.class).getSingleResult();
    em.close();
    assertEquals(book2.getName(), "Updated!");

}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.jpa.ArticleHandler.java

/**
 * Add or update a news article in the db
 *
 * @param entity The NewsItem//from w  w  w.  j ava  2  s  . c  o  m
 */
public void add(UXBEntity entity) throws Exception {

    Article art = buildArticle(entity);

    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 = :fsid AND x.language=:language").toString());
        query.setParameter("fsid", art.getAid());
        query.setParameter("language", art.getLanguage());

        /*
        * If the item exists in the db, we update the content and the title of the existing item
        */
        if (query.getResultList().size() > 0) {
            Article db = (Article) query.getSingleResult();
            db.setContent(art.getContent());
            db.setTitle(art.getTitle());
            db.setUrl(art.getUrl());
            db.setCreated(art.getCreated());
            db.setAid(art.getAid());
            db.setLanguage(art.getLanguage());
            db.setVersion(art.getVersion());
            db.setLastmodified(art.getLastmodified());

            art = db;
        }
        // save to db
        em.persist(art);
        em.flush();

        tx.commit();
    } catch (Exception e) {
        if (tx != null) {
            tx.setRollbackOnly();
            throw e;
        }
        logger.error("Failure while writing to the database", e);
    } finally {
        if (tx != null && tx.isActive()) {
            if (tx.getRollbackOnly()) {
                tx.rollback();
            }
        }
        if (em != null) {
            em.close();
        }
    }
}

From source file:br.usp.ime.lapessc.xflow2.core.VCSMiner.java

private void buildAndStoreCommit(VCSMiningProject miningProject, CommitDTO commitDTO) {

    Commit commit = new Commit();

    commit.setAuthor(getAuthor(commitDTO));
    commit.setComment(commitDTO.getComment());
    commit.setDate(commitDTO.getDate());
    commit.setRevision(commitDTO.getRevision());
    commit.setVcsMiningProject(miningProject);
    commit.setEntryFiles(getEntryFiles(commitDTO));
    commit.setEntryFolders(getEntryFolders(commitDTO));

    try {//w  ww .  java  2  s  . c o  m
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.persist(commit);
        manager.getTransaction().commit();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }

    fixOperationType(commit);

    //Fix parent folder for folders
    for (Folder folder : commit.getEntryFolders()) {
        fixFolder(folder, commit);
    }

    //Fix parent folder for files
    setParentFolders(commit);

    setDeletedOnForFileArtifacts(commit);
    setDeletedOnForFolders(commit);

    if (miningProject.getMiningSettings().isCodeDownloadEnabled()) {
        setLocMeasures(commit);
    }

    try {
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.flush();
        manager.getTransaction().commit();
        manager.clear();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }
}

From source file:com.google.inject.persist.jpa.KuneJpaLocalTxnInterceptor.java

@Override
public Object invoke(final MethodInvocation methodInvocation) throws Throwable, DefaultException {

    // Should we start a unit of work?
    if (!emProvider.isWorking()) {
        emProvider.begin();/*from w w w  .java  2s  . c om*/
        didWeStartWork.set(true);
        LOG.debug("Starting transaction");
    }

    final KuneTransactional transactional = readTransactionMetadata(methodInvocation);
    final EntityManager em = this.emProvider.get();

    // Allow 'joining' of transactions if there is an enclosing
    // @KuneTransactional method.
    if (em.getTransaction().isActive()) {
        LOG.debug("Joining a previous transaction");
        return methodInvocation.proceed();
    }

    final EntityTransaction txn = em.getTransaction();
    txn.begin();

    Object result;
    try {
        result = methodInvocation.proceed();

    } catch (final Exception e) {
        // commit transaction only if rollback didnt occur
        LOG.debug("Exception in transaction", e);
        if (rollbackIfNecessary(transactional, e, txn)) {
            txn.commit();
        }

        // propagate whatever exception is thrown anyway
        throw e;
    } finally {
        // Close the em if necessary (guarded so this code doesn't run unless
        // catch fired).
        if (null != didWeStartWork.get() && !txn.isActive()) {
            didWeStartWork.remove();
            unitOfWork.end();
        }
    }

    // everything was normal so commit the txn (do not move into try block above
    // as it
    // interferes with the advised method's throwing semantics)
    try {
        LOG.debug("Trying to commit transaction");
        txn.commit();
    } finally {
        LOG.debug("Transaction commited");
        // close the em if necessary
        if (null != didWeStartWork.get()) {
            didWeStartWork.remove();
            unitOfWork.end();
        }
    }

    // or return result
    return result;
}

From source file:com.espirit.moddev.examples.uxbridge.newswidget.test.CommandITCase.java

/**
 * Before test.// www . ja va 2  s.c om
 *
 * @throws Exception the exception
 */
@Before
public void beforeTest() throws Exception {
    EntityManager em = emf.createEntityManager();

    EntityTransaction tx = em.getTransaction();
    tx.begin();
    em.createQuery("DELETE FROM article").executeUpdate();
    tx.commit();
    em.close();
}