Example usage for javax.persistence EntityManager createNamedQuery

List of usage examples for javax.persistence EntityManager createNamedQuery

Introduction

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

Prototype

public Query createNamedQuery(String name);

Source Link

Document

Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).

Usage

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

@Override
public boolean clearSkills(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {/*from  w  w w  . jav a  2 s.c om*/
        em.getTransaction().begin();

        Query query = em.createNamedQuery("UserSkill.clearSkillsForEmployee");
        query.setParameter("employee", employee);

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

    return success;
}

From source file:org.dragoneronca.nlp.wol.domain.WolDomainContext.java

public void updateScore(int id, double score) {
    WolDomainContext domainContext = WolDomainContext.getInstance();
    EntityManager entityManager = domainContext.getEntityManager();

    SemanticEdge edge = entityManager.find(SemanticEdge.class, id);
    if (edge == null || edge instanceof TermSemanticEdge) {
        Query q = entityManager.createNamedQuery("updateScoreTermSemanticEdge");
        q.setParameter(1, score).setParameter(2, id);

        q.executeUpdate();/*w w w  . j  a  va  2  s  .  c  om*/
    } else {
        Query q = entityManager.createNamedQuery("updateScoreSemanticEdge");
        q.setParameter(1, score).setParameter(2, id);

        q.executeUpdate();
    }
}

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

@Override
public boolean clearSkills(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {// w w w .j av  a 2s . co m
        em.getTransaction().begin();

        Query query = em.createNamedQuery("VacancySkill.clearSkillsForVacancy");
        query.setParameter("vacancy", vacancy);
        query.executeUpdate();

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

    return success;
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * List users in repository.//from ww  w  . j  a v a 2 s.  c om
 * 
 * @return Iterator over a collection of Strings, each being one user in the
 *         repository.
 * @throws UsersRepositoryException
 */
@SuppressWarnings("unchecked")
public Iterator<String> list() throws UsersRepositoryException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    try {
        return Collections.unmodifiableList(entityManager.createNamedQuery("listUserNames").getResultList())
                .iterator();

    } catch (PersistenceException e) {
        getLogger().debug("Failed to find user", e);
        throw new UsersRepositoryException("Failed to list users", e);
    } finally {
        entityManager.close();
    }
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBag findLastBag(final long albumId) {
    final EmCallback<ProposalBag> emCallback = new EmCallback<ProposalBag>(this.getEmf()) {

        @Override/*from   w  w w  .ja v  a 2  s  . c  o  m*/
        @SuppressWarnings("unchecked")
        protected ProposalBag executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final Query findLastBagQuery = em.createNamedQuery(ProposalBag.FIND_LAST_ALBUM_BAG);
            findLastBagQuery.setParameter("albumId", albumId);
            findLastBagQuery.setMaxResults(1);

            final ProposalBag bag = Iterables.getFirst(findLastBagQuery.getResultList(), null);
            return bag;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBranch findBranchByName(final long albumId, final String name) {
    final EmCallback<ProposalBranch> emCallback = new EmCallback<ProposalBranch>(this.getEmf()) {

        @Override//from   ww w  .  j av  a2s .  com
        @SuppressWarnings("unchecked")
        protected ProposalBranch executeWithEntityManager(final EntityManager em) throws PersistenceException {
            final Query findBranchByNameQuery = em.createNamedQuery(ProposalBranch.FIND_BRANCH_BY_NAME);
            findBranchByNameQuery.setParameter("albumId", albumId);
            findBranchByNameQuery.setParameter("name", name);

            final ProposalBranch bag = Iterables.getFirst(findBranchByNameQuery.getResultList(), null);
            return bag;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public List<ProposalBranch> findAllBranches(final long albumId) {
    final EmCallback<List<ProposalBranch>> emCallback = new EmCallback<List<ProposalBranch>>(this.getEmf()) {

        @Override//w  ww. j av a 2s.c om
        @SuppressWarnings("unchecked")
        protected List<ProposalBranch> executeWithEntityManager(final EntityManager em)
                throws PersistenceException {
            final Query findLastBagQuery = em.createNamedQuery(ProposalBranch.FIND_BRANCHES_OF_ALBUM);
            findLastBagQuery.setParameter("albumId", albumId);

            final List<ProposalBranch> branches = findLastBagQuery.getResultList();
            return branches;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public List<ProposalBag> findBagAncestry(final long branchId, final long until) {
    final EmCallback<List<ProposalBag>> emCallback = new EmCallback<List<ProposalBag>>(this.getEmf()) {

        @Override//from   www .j a  v  a  2s . c  o  m
        @SuppressWarnings("unchecked")
        protected List<ProposalBag> executeWithEntityManager(final EntityManager em)
                throws PersistenceException {
            final Query findLastBagQuery = em.createNamedQuery(ProposalBag.FIND_BRANCH_BAGS_UNTIL);
            findLastBagQuery.setParameter("branchId", branchId);
            findLastBagQuery.setParameter("until", until);
            findLastBagQuery.setMaxResults(DbProposalDao.PAGINATION_SIZE);

            final List<ProposalBag> branches = findLastBagQuery.getResultList();
            return branches;
        }
    };

    return emCallback.getReturnedValue();
}

From source file:com.webbfontaine.valuewebb.action.fcvr.FCVRSendScheduler.java

@Asynchronous
public QuartzTriggerHandle scheduleTask(@Expiration Date when, @IntervalCron String interval) {
    LOGGER.info("Started");

    long startTime = System.currentTimeMillis();

    synchronized (LOCK) { // allow only one async thread to do this

        EntityManager entityManager = (EntityManager) Component.getInstance("entityManager",
                ScopeType.STATELESS, true);
        List<Long> ttIDs = Utils.setDirectRead(entityManager.createNamedQuery(findSentTTIdsCI)).getResultList();

        LOGGER.debug("Found Sent TTs: {0}}", ttIDs);

        if (ttIDs.isEmpty()) {
            return null;
        }/*from w w  w.j a  va2  s  .  co  m*/

        if (!AuthenticatorBean.getDaemonIdentity().tryLogin()) {
            LOGGER.error("Can not login with 'daemon' identity to update TTs");
            return null;
        }
        try {

            for (Long ttId : ttIDs) {
                try {
                    TtGen ttGen = entityManager.find(TtGen.class, ttId);

                    LOGGER.debug("TT to sent to FCVR: {0}, status {1}", ttId, ttGen.getStatus());

                    if (!ttGen.getStatus().equals(TT_SENT)) { // already processed by other thread
                        continue;
                    }

                    new TTDataLoader(ttGen).processAll();

                    Message message = FCVRSender.getInstance().sendFCVR(ttGen);

                    if (FCVRHelper.transactionError(message)) {
                        LOGGER.error("SOGate respond with error for TT {0} with FCVR Number {1}. Error: {2}",
                                ttId, ttGen.getFcvrNum(), message.getProperties());
                        FCVRHelper.logExceptions(ttId, message);
                    } else {
                        if (FCVRHelper.transactionFailed(message)) {
                            FCVRHelper.logExceptions(ttId, message);

                            String remoteExceptionMessage = FCVRHelper.extractErrors(message);
                            FCVRHelper.appendErrorsToTT(ttGen, remoteExceptionMessage);

                            if (isFCVRAlreadyExists(remoteExceptionMessage)) {
                                LOGGER.warn(
                                        "FCVR already exists for TT with ID {0}, check logs for previous unexpected errors. TT status will be changed to Sent Ok.",
                                        ttId);
                                updateTT(ttGen, RESPONSE_OK); // ignore existance and change the status.
                            } else {
                                if (isAccessProblem(remoteExceptionMessage)) {
                                    LOGGER.warn(
                                            "Cannot complete transaction for FCVR document, got {0} for TT ID: {1}, document processing skipped.",
                                            remoteExceptionMessage, ttId);
                                } else {
                                    LOGGER.info(
                                            "Cannot complete transaction for FCVR document, TT ID: {0}, document status will be changed accordingly.",
                                            ttId);
                                    updateTT(ttGen, ERROR_RESPONSE);
                                }
                            }

                        } else {
                            if (FCVRHelper.transactionSucceeded(message)) {
                                LOGGER.info("FCVR transaction on TT {0} completed successfully", ttId);
                                updateTT(ttGen, RESPONSE_OK);
                            } else {
                                LOGGER.error("Unknown FCVR response for TT: {0}, message: {1}", ttId,
                                        message.getProperties());
                                throw new FCVRProcessingException(
                                        "Unknown FCVR reponse, remote document change is ");
                            }
                        }
                    }
                } catch (FCVRProcessingException e) {
                    Throwable cause = e.getCause();
                    if (isConnectionProblem(cause) || isLoginProblem(cause)) {
                        LOGGER.warn("{0}: Can not connect to TWM-FCVR. {1}", cause.getClass().getName(),
                                cause.getMessage());
                        break; // do not continue with next TT if connection problem
                    } else {
                        LOGGER.error("", e);
                    }
                }
            }
        } finally {
            AuthenticatorBean.getDaemonIdentity().logout();
        }
        LOGGER.debug("Processing took {0} ms", System.currentTimeMillis() - startTime);
        return null;
    }
}

From source file:org.nuxeo.theme.webwidgets.providers.PersistentProvider.java

@SuppressWarnings("unchecked")
public synchronized List<Widget> getWidgets(final String regionName) throws ProviderException {
    if (regionName == null) {
        throw new ProviderException("Region name is undefined.");
    }// w  w  w . j a v  a 2 s .co m

    try {
        return getPersistenceProvider().run(true, new RunCallback<List<Widget>>() {
            public List<Widget> runWith(EntityManager em) {
                Query query = em.createNamedQuery("Widget.findAll");
                query.setParameter("region", regionName);
                return query.getResultList();
            }
        });
    } catch (ClientException e) {
        throw new ProviderException(e);
    }

}