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:in.bookmylab.jpa.JpaDAO.java

/**
 * @param xrd//from   ww  w  .java  2  s .c o m
 * @param em
 */
private void fixAnalysisModesAndResourceType(ResourceBooking booking, EntityManager em, boolean isUpdate) {
    // Analysis modes deletion
    if (booking.analysisModes != null) {
        for (Iterator<AnalysisMode> itr = booking.analysisModes.iterator(); itr.hasNext();) {
            AnalysisMode a = itr.next();
            if (a.deleted) {
                if (isUpdate) {
                    em.remove(em.merge(a));
                }
                itr.remove(); // Remove from collection
            } else {
                // Attach resource type
                Query q = em.createNamedQuery("ResourceType.findByCode");
                ResourceType rt = (ResourceType) q
                        .setParameter("code", StringUtils.upperCase(a.resourceType.code)).getSingleResult();
                a.resourceType = rt;
                if (isUpdate) {
                    em.merge(a);
                }
            }
        }
    }
}

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

@SuppressWarnings("unchecked")
public List<Widgetprofile> rebuildFeaturedWidgetsCache() {
    List<Widgetprofile> widgetProfiles;
    EntityManager entityManager = getEntityManagerFactory().createEntityManager();
    Query wpQuery = entityManager.createNamedQuery("Widgetprofile.featured");
    widgetProfiles = (List<Widgetprofile>) wpQuery.getResultList();
    entityManager.close();/* w w w  .j  a v  a2  s. co  m*/

    Cache.getInstance().put("FeaturedWidgets", widgetProfiles, 3200);
    return widgetProfiles;
}

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

@SuppressWarnings("unchecked")
public SearchResults returnWidgetProfilesOrderedByDate(int rows, int offset) {
    List<Widgetprofile> widgetprofiles;
    EntityManager entityManager = getEntityManagerFactory().createEntityManager();
    Query wpQuery = entityManager.createNamedQuery("Widgetprofile.created");
    wpQuery.setFirstResult(offset);/*from   ww w .jav  a2  s .co m*/
    wpQuery.setMaxResults(rows);
    widgetprofiles = (List<Widgetprofile>) wpQuery.getResultList();
    entityManager.close();
    SearchResults sr = new SearchResults();
    sr.setWidgets(widgetprofiles);
    return sr;
}

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

public Widgetprofile findWidgetProfileByUri(String uri) {
    try {/*from  w w w.  j av  a 2 s .  co  m*/
        EntityManager entityManager = getEntityManagerFactory().createEntityManager();
        Query wpQuery = entityManager.createNamedQuery("Widgetprofile.findByUri");
        wpQuery.setParameter("uri", uri);
        Widgetprofile widgetProfile = (Widgetprofile) wpQuery.getSingleResult();
        //
        // Ensure dependent objects are available when detached
        //
        widgetProfile.getTags();
        widgetProfile.getActivities();
        widgetProfile.getDescription();
        widgetProfile.getFunctionalities();
        widgetProfile.getCategories();
        entityManager.close();
        return widgetProfile;
    } catch (NoResultException e) {
        return null;
    }

}

From source file:org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java

/**
 * {@inheritDoc}//from   w w  w .  ja va2  s .  c o  m
 * 
 * @see org.opencastproject.capture.admin.api.CaptureAgentStateService#getKnownAgents()
 */
public Map<String, Agent> getKnownAgents() {
    EntityManager em = null;
    User user = securityService.getUser();
    Organization org = securityService.getOrganization();
    String orgAdmin = org.getAdminRole();
    String[] roles = user.getRoles();
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("Agent.byOrganization");
        q.setParameter("org", securityService.getOrganization().getId());

        // Filter the results in memory if this user is not an administrator
        List<AgentImpl> agents = q.getResultList();
        if (!user.hasRole(SecurityConstants.GLOBAL_ADMIN_ROLE) && !user.hasRole(orgAdmin)) {
            for (Iterator<AgentImpl> iter = agents.iterator(); iter.hasNext();) {
                AgentImpl agent = iter.next();
                Set<String> schedulerRoles = agent.getSchedulerRoles();
                // If there are no roles associated with this capture agent, it is available to anyone who can pass the
                // coarse-grained web layer security
                if (schedulerRoles == null || schedulerRoles.isEmpty()) {
                    continue;
                }
                boolean hasSchedulerRole = false;
                for (String role : roles) {
                    if (schedulerRoles.contains(role)) {
                        hasSchedulerRole = true;
                        break;
                    }
                }
                if (!hasSchedulerRole) {
                    iter.remove();
                }
            }
        }

        // Build the map that the API defines as agent name->agent
        Map<String, Agent> map = new TreeMap<String, Agent>();
        for (AgentImpl agent : agents) {
            map.put(agent.getName(), agent);
        }
        return map;
    } finally {
        if (em != null)
            em.close();
    }
}

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

public Widgetprofile updateWidgetProfile(String uri, String name, String description, String icon) {
    EntityManager em = getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();/*from  w w  w  .  java 2 s . c  om*/
    Query wpQuery = em.createNamedQuery("Widgetprofile.findByUri");
    wpQuery.setParameter("uri", uri);
    Widgetprofile widgetprofile = (Widgetprofile) wpQuery.getSingleResult();
    if (widgetprofile != null) {
        widgetprofile.setName(name);
        widgetprofile.setUpdated(new Date());
        WidgetDescription desc = widgetprofile.getDescription();
        if (desc == null) {
            desc = new WidgetDescription();
            desc.setWid_id(widgetprofile.getId());
            widgetprofile.setDescription(desc);
        }
        desc.setDescription(description);
        em.persist(em.merge(widgetprofile));
    }
    em.getTransaction().commit();
    em.close();
    return widgetprofile;
}

From source file:com.xidu.framework.common.dao.impl.BaseDaoImpl.java

/**
 * /*from   www.ja  v a2  s . c o m*/
 * {@inheritDoc} overridden:
 * 
 * @Date : 2011-3-28
 * @see com.xidu.framework.common.dao.IBaseDao#countByNamedQuery(java.lang.String)
 * 
 */
@Override
public int countByNamedQuery(final String queryName) {

    return getJpaTemplate().execute(new JpaCallback<Integer>() {

        @Override
        public Integer doInJpa(EntityManager em) throws PersistenceException {
            Object countObj = em.createNamedQuery(queryName).getSingleResult();
            return Integer.parseInt(countObj.toString());
        }

    });
}

From source file:com.xidu.framework.common.dao.impl.BaseDaoImpl.java

/**
 * //from w w  w . j ava  2  s . c o m
 * {@inheritDoc} overridden:
 * 
 * @Date : 2011-3-28
 * @see com.xidu.framework.common.dao.IBaseDao#countByNamedQueryWithMap(java.lang.String,
 *      java.util.Map)
 * 
 */
@Override
public int countByNamedQueryWithMap(final String queryName, final Map<String, ?> paraMap) {

    return getJpaTemplate().execute(new JpaCallback<Integer>() {

        @Override
        public Integer doInJpa(EntityManager em) throws PersistenceException {

            Query namedQuery = em.createNamedQuery(queryName);
            prepareQueryParam(namedQuery, paraMap);

            Object countObj = namedQuery.getSingleResult();
            return Integer.parseInt(countObj.toString());
        }

    });
}

From source file:com.xidu.framework.common.dao.impl.BaseDaoImpl.java

/**
 * //from ww  w . j  ava  2s . c o m
 * {@inheritDoc} overridden:
 * 
 * @Date : 2011-3-28
 * @see com.xidu.framework.common.dao.IBaseDao#countByNamedQueryWithVaParam(java.lang.String,
 *      java.lang.Object[])
 * 
 */
@Override
public int countByNamedQueryWithVaParam(final String queryName, final Object... params) {

    return getJpaTemplate().execute(new JpaCallback<Integer>() {

        @Override
        public Integer doInJpa(EntityManager em) throws PersistenceException {

            Query namedQuery = em.createNamedQuery(queryName);
            prepareQueryParam(namedQuery, params);

            Object countObj = namedQuery.getSingleResult();
            return Integer.parseInt(countObj.toString());
        }

    });
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * {@inheritDoc}/*from ww w  . j  a va2  s .  c o m*/
 * 
 * @see org.eclipse.smila.connectivity.deltaindexing.DeltaIndexingManager#getEntryCount(String)
 */
@Override
public long getEntryCount(final String dataSourceId) {
    _lock.readLock().lock();
    try {
        final EntityManager em = createEntityManager();
        try {
            final Query query = em.createNamedQuery(DeltaIndexingDao.NAMED_QUERY_COUNT_ENTRIES_BY_SOURCE);
            final Long count = (Long) query
                    .setParameter(DeltaIndexingDao.NAMED_QUERY_PARAM_SOURCE, dataSourceId).getSingleResult();
            if (count == null) {
                return 0;
            }
            return count.longValue();
        } finally {
            closeEntityManager(em);
        }
    } catch (final DeltaIndexingException ex) {
        if (_log.isErrorEnabled()) {
            _log.error("error getting entry count for data source id " + dataSourceId, ex);
        }
        return 0;
    } finally {
        _lock.readLock().unlock();
    }
}