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:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

/**
 * Check registry for requested person, return a DzPatients object.
 * @param p//www .j  av a 2s  .c o m
 * @return  DzType registry type object
 */
private DzPatients validPerson(PersonType p) throws Exception, NoResultException {
    EntityManager em = null;
    PersistentServiceFactory psf = null;
    DzPatients registeredPatient = null;

    try {
        psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
        em = psf.getEntityManager();

        Query query = em.createNamedQuery("DzPatients.findByPatid");
        query.setParameter("patid", p.getId());
        registeredPatient = (DzPatients) query.getSingleResult();
    } catch (NoResultException nre) {
        throw nre;
    } catch (Exception ex) {
        throw new Exception("Person " + p.getId() + " not found;");
    } finally {
        em.close();
    }

    return registeredPatient;
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

public FootprintList getFootprints(String mediapackageId, String userId) {
    EntityManager em = null;
    try {//from ww w.java 2  s  .c  om
        em = emf.createEntityManager();
        Query q = null;
        if (StringUtils.trimToNull(userId) == null) {
            q = em.createNamedQuery("findUserActionsByTypeAndMediapackageIdOrderByOutpointDESC");
        } else {
            q = em.createNamedQuery("findUserActionsByTypeAndMediapackageIdByUserOrderByOutpointDESC");
            q.setParameter("userid", userId);
        }
        q.setParameter("type", FOOTPRINT_KEY);
        q.setParameter("mediapackageId", mediapackageId);
        @SuppressWarnings("unchecked")
        Collection<UserAction> userActions = q.getResultList();

        int[] resultArray = new int[1];
        boolean first = true;

        for (UserAction a : userActions) {
            if (first) {
                // Get one more item than the known outpoint to append a footprint of 0 views at the end of the result set
                resultArray = new int[a.getOutpoint() + 1];
                first = false;
            }
            for (int i = a.getInpoint(); i < a.getOutpoint(); i++) {
                resultArray[i]++;
            }
        }
        FootprintList list = new FootprintsListImpl();
        int current = -1;
        int last = -1;
        for (int i = 0; i < resultArray.length; i++) {
            current = resultArray[i];
            if (last != current) {
                Footprint footprint = new FootprintImpl();
                footprint.setPosition(i);
                footprint.setViews(current);
                list.add(footprint);
            }
            last = current;
        }
        return list;
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

/**
 * Returns a list of available registry types.
 * @return  List<RegistryType>/* www  .  j a  va  2  s .c o m*/
 */
public List<RegistryType> getRegistryTypes() {
    EntityManager em = null;
    List<RegistryType> types = new ArrayList<RegistryType>();
    PersistentServiceFactory psf = null;

    try {
        psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
        em = psf.getEntityManager();

        Query query = em.createNamedQuery("DzType.findAll");
        Collection<DzType> results = query.getResultList();

        for (DzType d : results) {
            log.debug(d.toString());
            types.add(new RegistryType(d.getDztypeId(), d.getDescr()));
        }
    } catch (javax.persistence.NoResultException nr) {
        log.error(nr);
    } finally {
        em.close();
    }

    return types;
}

From source file:org.opencastproject.usertracking.impl.UserTrackingServiceImpl.java

@SuppressWarnings("unchecked")
public UserAction addUserFootprint(UserAction a) throws UserTrackingException {
    a.setType("FOOTPRINT");
    EntityManager em = null;
    EntityTransaction tx = null;//from   www .  j ava 2 s.c  o m
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        Query q = em.createNamedQuery("findLastUserFootprintOfSession");
        q.setMaxResults(1);
        q.setParameter("sessionId", a.getSessionId());
        Collection<UserAction> userActions = q.getResultList();

        if (userActions.size() >= 1) {
            UserAction last = userActions.iterator().next();
            if (last.getMediapackageId().equals(a.getMediapackageId()) && last.getType().equals(a.getType())
                    && last.getOutpoint() == a.getInpoint()) {
                last.setOutpoint(a.getOutpoint());
                a = last;
                a.setId(last.getId());
            } else {
                em.persist(a);
            }
        } else {
            em.persist(a);
        }
        tx.commit();
        return a;
    } catch (Exception e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        throw new UserTrackingException(e);
    } finally {
        if (em != null && em.isOpen()) {
            em.close();
        }
    }
}

From source file:org.exoplatform.social.addons.storage.RDBMSIdentityStorageImpl.java

/**
 * This method is introduced to clean totally identity from database
 * It's used in unit test/*from  w w  w .j  a va  2 s .  c  o m*/
 * @param identity the Identity
 */
@ExoTransactional
public void removeIdentity(Identity identity) {
    long id = EntityConverterUtils.parseId(identity.getId());
    String username = identity.getRemoteId();
    String provider = identity.getProviderId();

    IdentityEntity entity = getIdentityDAO().find(id);

    EntityManager em = CommonsUtils.getService(EntityManagerService.class).getEntityManager();
    Query query;

    // Delete all connection
    query = em.createNamedQuery("SocConnection.deleteConnectionByIdentity");
    query.setParameter("identityId", id);
    query.executeUpdate();

    if (OrganizationIdentityProvider.NAME.equals(provider)) {
        // Delete space-member
        query = em.createNamedQuery("SpaceMember.deleteByUsername");
        query.setParameter("username", username);
        query.executeUpdate();
    }

    if (entity != null) {
        getIdentityDAO().delete(entity);
    }
}

From source file:org.exoplatform.social.addons.storage.RDBMSIdentityStorageImpl.java

/**
 * Hard delete an identity from JCR// w w  w  . j a va  2  s. c  om
 *
 * @param identity the identity to be deleted
 * @throws IdentityStorageException if has any error
 */
@ExoTransactional
public void hardDeleteIdentity(final Identity identity) throws IdentityStorageException {
    long id = EntityConverterUtils.parseId(identity.getId());
    String username = identity.getRemoteId();
    String provider = identity.getProviderId();

    IdentityEntity entity = getIdentityDAO().find(id);
    if (entity != null) {
        entity.setDeleted(true);
        getIdentityDAO().update(entity);
    }

    if (entity.getAvatarFileId() != null && entity.getAvatarFileId() > 0) {
        fileService.deleteFile(entity.getAvatarFileId());
    }

    EntityManager em = CommonsUtils.getService(EntityManagerService.class).getEntityManager();
    Query query;

    // Delete all connection
    query = em.createNamedQuery("SocConnection.deleteConnectionByIdentity");
    query.setParameter("identityId", id);
    query.executeUpdate();

    if (OrganizationIdentityProvider.NAME.equals(provider)) {
        // Delete space-member
        query = em.createNamedQuery("SpaceMember.deleteByUsername");
        query.setParameter("username", username);
        query.executeUpdate();
    }
}

From source file:mil.navy.med.dzreg.dao.RegistriesManagerDAO.java

/**
 * Returns the registry profile of a person.
 * @param personId  unique identifier of person
 * @return  PersonRegistryProfileType//from   w ww .j a v a 2  s .  c o m
 */
public PersonRegistryProfileType getRegistryProfile(Long personId) {
    EntityManager em = null;
    PersonRegistryProfileType profile = null;
    PersistentServiceFactory psf = null;

    if (personId != null) {
        try {
            psf = PersistentServiceFactory.getInstance(REGISTRY_MANAGER_PU);
            em = psf.getEntityManager();

            Query query = em.createNamedQuery("DzPatients.findByPatid");
            query.setParameter("patid", personId);
            DzPatients result = (DzPatients) query.getSingleResult();

            if (result != null) {
                em.refresh(result);
                //log.debug(result.toString());
                try {
                    profile = map(result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (javax.persistence.NoResultException nr) {
            log.error("No data found for personId=" + personId);
        } finally {
            em.close();
        }
    } else {
        log.error("personId can not be null or empty");
    }

    return profile;
}

From source file:commonSession.PersistAttivitaFacadeBean.java

public List resultListQuery(String nomeQuery, Map<String, Object> parametri, String unit) throws Exception {

    //    EntityManager em;
    EntityManager em = GestionaleEm;

    //    if(unit.equals("GestionaleEm")) em = GestionaleEm;
    //        else em = TerrEm;

    Query q = em.createNamedQuery(nomeQuery);
    for (String key : parametri.keySet()) {
        q.setParameter(key, parametri.get(key));
    }/*ww w  .j  a  va  2s.c  o m*/

    //    System.out.println("persist: "+q);

    return q.getResultList();
}

From source file:uk.ac.edukapp.service.WidgetProfileService.java

public List<Widgetprofile> getWidgetsForUser(Useraccount owner) {
    EntityManager em = getEntityManagerFactory().createEntityManager();
    Query q = em.createNamedQuery("Widgetprofile.ownedBy");
    q.setParameter("user", owner);
    @SuppressWarnings("unchecked")
    List<Widgetprofile> results = q.getResultList();
    em.close();//from ww w.  j ava 2 s.co m
    return results;
}

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

@SuppressWarnings("unchecked")
public List<MessageSignature> getMessageSignatures() throws MailServiceException {
    EntityManager em = null;
    try {//from   w w  w  .  j a v a  2s. com
        em = emf.createEntityManager();
        String orgId = securityService.getOrganization().getId();
        Query q = em.createNamedQuery("MessageSignature.findAll").setParameter("org", orgId);
        List<MessageSignature> signatures = new ArrayList<MessageSignature>();
        List<MessageSignatureDto> result = q.getResultList();
        for (MessageSignatureDto m : result) {
            signatures.add(m.toMessageSignature(userDirectoryService));
        }
        return signatures;
    } catch (Exception e) {
        logger.error("Could not get message signatures: {}", e.getMessage());
        throw new MailServiceException(e);
    } finally {
        if (em != null)
            em.close();
    }
}