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 <T> TypedQuery<T> createNamedQuery(String name, Class<T> resultClass);

Source Link

Document

Create an instance of TypedQuery for executing a Java Persistence query language named query.

Usage

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*www.  j  a v  a  2  s  .c  o m*/
 */
@Override
public <T extends BaseEntity> int deleteByJpaNamedQuery(CrudDTO<T> crudDTO) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        TypedQuery<T> typedQuery = em.createNamedQuery(crudDTO.getNamedQuery(), crudDTO.getEntity());
        JpaUtil.bindQueryParams(typedQuery, crudDTO.getPosParams());
        int rowsDeleted = typedQuery.executeUpdate();
        em.getTransaction().commit();
        LOGGER.debug("deleteByJpaNamedQuery: 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:org.opencastproject.messages.MailService.java

@SuppressWarnings("unchecked")
public List<MessageTemplate> getMessageTemplates() throws MailServiceException {
    EntityManager em = null;
    try {/*ww w.  java2  s .co m*/
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        TypedQuery<MessageTemplateDto> q = em
                .createNamedQuery("MessageTemplate.findAll", MessageTemplateDto.class)
                .setParameter("org", orgId);
        List<MessageTemplate> templates = new ArrayList<MessageTemplate>();
        List<MessageTemplateDto> result = q.getResultList();
        for (MessageTemplateDto m : result) {
            templates.add(m.toMessageTemplate(userDirectoryService));
        }
        return templates;
    } catch (Exception e) {
        logger.error("Could not get message templates: {}", ExceptionUtils.getStackTrace(e));
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

@SuppressWarnings("unchecked")
public List<MessageTemplate> getMessageTemplateByName(String messageTemplateName) throws MailServiceException {
    EntityManager em = null;
    try {//from   w w w  .  ja v a2  s  .co  m
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        TypedQuery<MessageTemplateDto> q = em
                .createNamedQuery("MessageTemplate.findByName", MessageTemplateDto.class)
                .setParameter("org", orgId);
        q.setParameter("name", messageTemplateName);
        List<MessageTemplate> templates = new ArrayList<MessageTemplate>();
        List<MessageTemplateDto> result = q.getResultList();
        for (MessageTemplateDto m : result) {
            templates.add(m.toMessageTemplate(userDirectoryService));
        }
        return templates;
    } catch (Exception e) {
        logger.error("Could not get message templates: {}", ExceptionUtils.getStackTrace(e));
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

@SuppressWarnings("unchecked")
public List<MessageTemplate> getMessageTemplatesStartingWith(String filterText) throws MailServiceException {
    EntityManager em = null;
    try {//  w w w .j  a va 2  s.  c o m
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        TypedQuery<MessageTemplateDto> q = em
                .createNamedQuery("MessageTemplate.likeName", MessageTemplateDto.class)
                .setParameter("org", orgId);
        q.setParameter("name", filterText + "%");
        List<MessageTemplate> templates = new ArrayList<MessageTemplate>();
        List<MessageTemplateDto> result = q.getResultList();
        for (MessageTemplateDto m : result) {
            templates.add(m.toMessageTemplate(userDirectoryService));
        }
        return templates;
    } catch (Exception e) {
        logger.error("Could not get message templates: {}", ExceptionUtils.getStackTrace(e));
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.messages.MailService.java

/**
 * Get the current logged in user's signature
 * @return The message signature/*from  w  w  w.  j  a  va2  s . co  m*/
 * @throws UserSettingsServiceException
 */
public MessageSignature getCurrentUsersSignature() throws MailServiceException, NotFoundException {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        String username = securityService.getUser().getUsername();
        TypedQuery<MessageSignatureDto> q = em
                .createNamedQuery("MessageSignature.findByCreator", MessageSignatureDto.class)
                .setParameter("username", username).setParameter("org", orgId);
        MessageSignatureDto messageSignatureDto = q.getSingleResult();
        return messageSignatureDto.toMessageSignature(userDirectoryService);
    } catch (NoResultException e) {
        throw new NotFoundException(e);
    } catch (Exception e) {
        logger.error("Could not get message signatures: {}", ExceptionUtils.getStackTrace(e));
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

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 {/*from  ww  w .j a  va  2 s .  c om*/
        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:com.epam.training.taranovski.web.project.repository.implementation.VacancyRepositoryImplementation.java

@Override
public List<Employee> getAppropriateAvailableEmployees(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    List<Integer> list = null;
    List<Employee> list1 = new LinkedList<>();

    try {/* w  ww.j a v  a 2 s  .  c  om*/
        em.getTransaction().begin();

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

        TypedQuery<Employee> query1 = em.createNamedQuery("Employee.findAmongIdsFreeEmployees", Employee.class);
        query1.setParameter("employeeIdList", list);
        list1 = query1.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 list1;
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Find all @AlertHistoryEntity with date before provided date.
 * @param clusterId cluster id//from  w ww.  j  a v  a2  s . c  o m
 * @param beforeDateMillis timestamp in millis
 * @return List<Integer> ids
 */
private List<Integer> findAllAlertHistoryIdsBeforeDate(Long clusterId, long beforeDateMillis) {

    EntityManager entityManager = m_entityManagerProvider.get();
    TypedQuery<Integer> alertHistoryQuery = entityManager
            .createNamedQuery("AlertHistoryEntity.findAllIdsInClusterBeforeDate", Integer.class);

    alertHistoryQuery.setParameter("clusterId", clusterId);
    alertHistoryQuery.setParameter("beforeDate", beforeDateMillis);

    return m_daoUtils.selectList(alertHistoryQuery);
}

From source file:org.apache.ambari.server.orm.dao.AlertsDAO.java

/**
 * Removes alert history and current alerts for the specified alert defintiion
 * ID. This will invoke {@link EntityManager#clear()} when completed since the
 * JPQL statement will remove entries without going through the EM.
 *
 * @param definitionId//from w  w  w  . j  av  a2s.  co  m
 *          the ID of the definition to remove.
 */
@Transactional
public void removeByDefinitionId(long definitionId) {
    EntityManager entityManager = m_entityManagerProvider.get();
    TypedQuery<AlertCurrentEntity> currentQuery = entityManager
            .createNamedQuery("AlertCurrentEntity.removeByDefinitionId", AlertCurrentEntity.class);

    currentQuery.setParameter("definitionId", definitionId);
    currentQuery.executeUpdate();

    TypedQuery<AlertHistoryEntity> historyQuery = entityManager
            .createNamedQuery("AlertHistoryEntity.removeByDefinitionId", AlertHistoryEntity.class);

    historyQuery.setParameter("definitionId", definitionId);
    historyQuery.executeUpdate();

    entityManager.clear();

    // if caching is enabled, invalidate the cache to force the latest values
    // back from the DB
    if (m_configuration.isAlertCacheEnabled()) {
        m_currentAlertCache.invalidateAll();
    }
}

From source file:com.enioka.jqm.api.HibernateClient.java

@Override
public int enqueue(JobRequest jd) {
    jqmlogger.trace("BEGINING ENQUEUE");
    EntityManager em = getEm();
    JobDef job = null;//from www .j a  v  a 2 s  .c  om
    try {
        job = em.createNamedQuery("HibApi.findJobDef", JobDef.class)
                .setParameter("applicationName", jd.getApplicationName()).getSingleResult();
    } catch (NoResultException ex) {
        jqmlogger.error("Job definition named " + jd.getApplicationName() + " does not exist");
        closeQuietly(em);
        throw new JqmInvalidRequestException("no job definition named " + jd.getApplicationName());
    }

    jqmlogger.trace("Job to enqueue is from JobDef " + job.getId());
    Integer hl = null;
    List<RuntimeParameter> jps = overrideParameter(job, jd, em);

    // Begin transaction (that will hold a lock in case of Highlander)
    try {
        em.getTransaction().begin();

        if (job.isHighlander()) {
            hl = highlanderMode(job, em);
        }

        if (hl != null) {
            jqmlogger.trace(
                    "JI won't actually be enqueued because a job in highlander mode is currently submitted: "
                            + hl);
            closeQuietly(em);
            return hl;
        }
        jqmlogger.trace("Not in highlander mode or no currently enqueued instance");
    } catch (Exception e) {
        closeQuietly(em);
        throw new JqmClientException("Could not do highlander analysis", e);
    }

    try {
        Queue q = job.getQueue();
        if (jd.getQueueName() != null) {
            q = em.createNamedQuery("HibApi.findQueue", Queue.class).setParameter("name", jd.getQueueName())
                    .getSingleResult();
        }

        JobInstance ji = new JobInstance();
        ji.setJd(job);

        ji.setState(State.SUBMITTED);
        ji.setQueue(q);
        ji.setNode(null);
        ji.setApplication(jd.getApplication());
        ji.setEmail(jd.getEmail());
        ji.setKeyword1(jd.getKeyword1());
        ji.setKeyword2(jd.getKeyword2());
        ji.setKeyword3(jd.getKeyword3());
        ji.setModule(jd.getModule());
        ji.setProgress(0);
        ji.setSessionID(jd.getSessionID());
        ji.setUserName(jd.getUser());

        ji.setCreationDate(Calendar.getInstance());
        if (jd.getParentID() != null) {
            ji.setParentId(jd.getParentID());
        }
        em.persist(ji);

        // There is sadly no portable and easy way to get DB time before insert... so we update afterwards.
        // Also updates the internal queue position marker (done in update and not setter to avoid full stupid JPA update).
        em.createNamedQuery("HibApi.updateJiWithDbTime").setParameter("i", ji.getId()).executeUpdate();

        for (RuntimeParameter jp : jps) {
            jqmlogger.trace("Parameter: " + jp.getKey() + " - " + jp.getValue());
            em.persist(ji.addParameter(jp.getKey(), jp.getValue()));
        }

        jqmlogger.trace("JI just created: " + ji.getId());
        em.getTransaction().commit();
        return ji.getId();
    } catch (NoResultException e) {
        throw new JqmInvalidRequestException("An entity specified in the execution request does not exist", e);
    } catch (Exception e) {
        throw new JqmClientException("Could not create new JobInstance", e);
    } finally {
        closeQuietly(em);
    }
}