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:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java

public int countComments() throws EventCommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    Query query = em.createNamedQuery("EventComment.countAll");
    try {/*from www .j  a v  a2s .  c  o  m*/
        Number total = (Number) query.getSingleResult();
        return total.intValue();
    } catch (Exception e) {
        logger.error("Could not find the number of comments.", e);
        throw new EventCommentDatabaseException(e);
    } finally {
        em.close();
    }
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

/**
 * {@inheritDoc}//from   w  ww  .  j a v  a  2  s .c  o m
 * 
 * @see org.opencastproject.security.api.RoleDirectoryService#getRoles()
 */
@Override
public String[] getRoles() {
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("roles");
        @SuppressWarnings("unchecked")
        List<String> results = q.getResultList();
        return results.toArray(new String[results.size()]);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.themes.persistence.ThemesServiceDatabaseImpl.java

/**
 * Gets a theme by its ID, using the current organizational context.
 *
 * @param id/*  www  . j  a va  2  s . c om*/
 *          the theme identifier
 * @param em
 *          an open entity manager
 * @return the theme entity, or null if not found
 */
private ThemeDto getThemeDto(long id, EntityManager em) {
    String orgId = securityService.getOrganization().getId();
    Query q = em.createNamedQuery("Themes.findById").setParameter("id", id).setParameter("org", orgId);
    try {
        return (ThemeDto) q.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

public User loadUser(String userName, String organizationId) {
    EntityManager em = null;
    try {//from   ww w.ja  va 2  s  .  c om
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("user");
        q.setParameter("u", userName);
        q.setParameter("o", organizationId);
        JpaUser user = null;
        try {
            user = (JpaUser) q.getSingleResult();
        } catch (NoResultException e) {
            return null;
        }
        Set<String> roles = user.getRoles();
        return new User(userName, user.getPassword(), user.getOrganization(),
                roles.toArray(new String[roles.size()]));
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java

@SuppressWarnings("unchecked")
public Iterator<EventCommentDto> getComments() throws EventCommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    try {/*from   w ww .  jav  a2 s . co m*/
        Query q = em.createNamedQuery("EventComment.findAll");
        return new ArrayList<EventCommentDto>(q.getResultList()).iterator();
    } catch (Exception e) {
        logger.error("Could not retreive event comments: {}", ExceptionUtils.getStackTrace(e));
        throw new EventCommentDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

public int countSeries() throws SeriesServiceDatabaseException {
    EntityManager em = emf.createEntityManager();
    Query query = em.createNamedQuery("Series.getCount");
    try {//  ww  w  . ja v a2s  .com
        Long total = (Long) query.getSingleResult();
        return total.intValue();
    } catch (Exception e) {
        logger.error("Could not find number of series.", e);
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

@GET
@Produces(MediaType.APPLICATION_JSON)//from  ww  w .j a  va  2 s .  co m
@Path("users.json")
@RestQuery(name = "allusers", description = "Returns a list of users", returnDescription = "Returns a JSON representation of the list of user accounts", restParameters = {
        @RestParameter(defaultValue = "0", description = "The maximum number of items to return per page.", isRequired = false, name = "limit", type = RestParameter.Type.STRING),
        @RestParameter(defaultValue = "0", description = "The page number.", isRequired = false, name = "offset", type = RestParameter.Type.STRING) }, reponses = {
                @RestResponse(responseCode = SC_OK, description = "The user accounts.") })
@SuppressWarnings("unchecked")
public String getUsersAsJson(@QueryParam("limit") int limit, @QueryParam("offset") int offset)
        throws IOException {
    if (limit < 1) {
        limit = 100;
    }
    EntityManager em = null;
    try {
        em = emf.createEntityManager();
        Query q = em.createNamedQuery("users").setMaxResults(limit).setFirstResult(offset);
        q.setParameter("o", securityService.getOrganization().getId());
        List<JpaUser> jpaUsers = q.getResultList();
        JSONArray jsonArray = new JSONArray();
        for (JpaUser user : jpaUsers) {
            Set<String> roles = user.getRoles();
            jsonArray.add(toJson(new User(user.getUsername(), user.getOrganization(),
                    roles.toArray(new String[roles.size()]))));
        }
        return jsonArray.toJSONString();
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.comments.events.persistence.EventCommentDatabaseServiceImpl.java

@Override
@SuppressWarnings("unchecked")
public List<String> getReasons() throws EventCommentDatabaseException {
    EntityManager em = emf.createEntityManager();
    try {//from  ww  w . j  av a 2 s  .c om
        Query q = em.createNamedQuery("EventComment.findReasons");
        q.setParameter("org", securityService.getOrganization().getId());
        return q.getResultList();
    } catch (Exception e) {
        logger.error("Could not get reasons: {}", ExceptionUtils.getStackTrace(e));
        throw new EventCommentDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:org.opencastproject.series.impl.persistence.SeriesServiceDatabaseImpl.java

@SuppressWarnings("unchecked")
@Override/*from  w w  w .  j a  va 2 s.c  om*/
public Iterator<Tuple<DublinCoreCatalog, String>> getAllSeries() throws SeriesServiceDatabaseException {
    EntityManager em = emf.createEntityManager();
    Query query = em.createNamedQuery("Series.findAll");
    List<SeriesEntity> seriesEntities = null;
    try {
        seriesEntities = (List<SeriesEntity>) query.getResultList();
    } catch (Exception e) {
        logger.error("Could not retrieve all series: {}", e.getMessage());
        throw new SeriesServiceDatabaseException(e);
    } finally {
        em.close();
    }
    List<Tuple<DublinCoreCatalog, String>> seriesList = new LinkedList<Tuple<DublinCoreCatalog, String>>();
    try {
        for (SeriesEntity entity : seriesEntities) {
            DublinCoreCatalog dc = parseDublinCore(entity.getDublinCoreXML());
            seriesList.add(Tuple.tuple(dc, entity.getOrganization()));
        }
    } catch (Exception e) {
        logger.error("Could not parse series entity: {}", e.getMessage());
        throw new SeriesServiceDatabaseException(e);
    }
    return seriesList.iterator();
}

From source file:in.bookmylab.jpa.JpaDAO.java

/**
 * @param spmId /*from   w w w .j a va2  s  .com*/
 * @return
 */
public SpmLabBooking getSpmBooking(Long spmId) {
    EntityManager em = emf.createEntityManager();
    SpmLabBooking spm = null;
    try {
        Query q = em.createNamedQuery("SpmLabBooking.findById");
        spm = (SpmLabBooking) q.setParameter("spmId", spmId).getSingleResult();
    } finally {
        em.close();
    }
    return spm;
}