Example usage for javax.persistence EntityManager createQuery

List of usage examples for javax.persistence EntityManager createQuery

Introduction

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

Prototype

public <T> TypedQuery<T> createQuery(String qlString, Class<T> resultClass);

Source Link

Document

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

Usage

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.DocumentSetCoverController.java

/**
 * Gets the size of a set cover (number of covered documents).
 * @param em the {@link EntityManager} to use.
 * @param setCover the {@link DocumentSetCover} whose size is required.
 * @return the {@link Long} count of documents.
 *///ww w.  j  av  a  2s.  c om
public long getCoverSize(EntityManager em, DocumentSetCover setCover) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(setCover, CannedMessages.NULL_ARGUMENT, "setCover");

    TypedQuery<byte[]> query = em.createQuery(
            "SELECT scd.id FROM SetCoverDocument scd " + "WHERE scd.store=:sc " + "AND scd.flag=true",
            byte[].class);
    query.setParameter("sc", setCover);

    return query.getResultList().size();
}

From source file:com.yahoo.sql4d.indexeragent.meta.DBHandler.java

public DataSource getDataSource(String tableName) {
    EntityManager em = getEntityManager();
    try {/*from   w w w  .  j a  v  a 2s  .  co m*/
        List<DataSource> resultList = em
                .createQuery("SELECT ds FROM DataSource ds WHERE ds.name = :name", DataSource.class)
                .setParameter("name", tableName).getResultList();
        return resultList.isEmpty() ? null : resultList.get(0);
    } finally {
        em.close();
    }
}

From source file:com.ewcms.common.query.jpa.QueryInit.java

private boolean isAlreadyInit() {
    return getJpaTemplate().execute(new JpaCallback<Boolean>() {
        @Override// w  w  w.  j a va  2 s.com
        public Boolean doInJpa(EntityManager em) throws PersistenceException {
            String hql = "Select count(o.id) From Certificate o";
            int count = em.createQuery(hql, Long.class).getSingleResult().intValue();
            return count > 0;
        }

    });
}

From source file:cz.fi.muni.pa165.dto.BookDAOTest.java

@Test
public void testUpdate() {
    EntityManager em = emf.createEntityManager();
    BookDAOImpl bdao = new BookDAOImpl();
    bdao.setManager(em);//  ww w.  j  a v a 2s .co m
    Book book = new Book();
    book = em.createQuery("SELECT b FROM Book b", Book.class).getSingleResult();
    em.getTransaction().begin();
    book.setName("Updated!");
    bdao.update(book);
    em.getTransaction().commit();

    Book book2 = em.createQuery("SELECT b FROM Book b", Book.class).getSingleResult();
    em.close();
    assertEquals(book2.getName(), "Updated!");

}

From source file:fr.univrouen.poste.domain.PosteCandidature.java

public static Long countFindPosteCandidaturesByPostesAndCandidatsAndRecevableAndAuditionnableAndModification(
        List<PosteAPourvoir> postes, List<User> candidats, List<ReviewStatusTypes> reviewStatus,
        Boolean recevable, Boolean auditionnable, Boolean modification) {
    EntityManager em = entityManager();
    String jpaQuery = "SELECT COUNT(o) FROM PosteCandidature AS o WHERE";
    if (postes != null) {
        jpaQuery = jpaQuery + " o.poste IN :postes AND";
    }//w  ww  .j  a va2 s .  co  m
    if (candidats != null) {
        jpaQuery = jpaQuery + " o.candidat IN :candidats AND";
    }
    if (reviewStatus != null) {
        jpaQuery = jpaQuery + " o.managerReview.reviewStatus IN :reviewStatus AND";
    }
    if (recevable != null) {
        jpaQuery = jpaQuery + " o.recevable = :recevable AND";
    }
    if (auditionnable != null) {
        jpaQuery = jpaQuery + " o.auditionnable = :auditionnable AND";
    }
    if (modification != null) {
        if (modification) {
            jpaQuery = jpaQuery + " o.modification IS NOT NULL AND";
        } else {
            jpaQuery = jpaQuery + " o.modification IS NULL AND";
        }
    }
    jpaQuery = jpaQuery + " 1=1";
    TypedQuery q = em.createQuery(jpaQuery, Long.class);
    if (postes != null) {
        q.setParameter("postes", postes);
    }
    if (candidats != null) {
        q.setParameter("candidats", candidats);
    }
    if (reviewStatus != null) {
        q.setParameter("reviewStatus", reviewStatus);
    }
    if (recevable != null) {
        q.setParameter("recevable", recevable);
    }
    if (auditionnable != null) {
        q.setParameter("auditionnable", auditionnable);
    }
    return ((Long) q.getSingleResult());
}

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

@GET
@Path("file")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public InputStream getDeliverableStream(@QueryParam("id") String randomId) {
    if (n == null) {
        throw new ErrorDto("can only retrieve a file when the web app runs on top of JQM", "", 7,
                Status.BAD_REQUEST);/*  w  w  w . j  av a 2 s  . co  m*/
    }

    Deliverable d = null;
    EntityManager em = null;
    try {
        em = ((HibernateClient) JqmClientFactory.getClient()).getEm();
        d = em.createQuery("SELECT d from Deliverable d WHERE d.randomId = :ii", Deliverable.class)
                .setParameter("ii", randomId).getSingleResult();
    } catch (NoResultException e) {
        throw new ErrorDto("Deliverable does not exist", 8, e, Status.BAD_REQUEST);
    } catch (Exception e) {
        throw new ErrorDto("Could not retrieve Deliverable metadata from database", 9, e,
                Status.INTERNAL_SERVER_ERROR);
    } finally {
        if (em != null) {
            em.close();
        }
    }

    String ext = FilenameUtils.getExtension(d.getOriginalFileName());
    res.setHeader("Content-Disposition",
            "attachment; filename=" + d.getFileFamily() + "." + d.getId() + "." + ext);
    return getFile(FilenameUtils.concat(n.getDlRepo(), d.getFilePath()));
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.entitymanagers.LexiconController.java

/**
 * Gets all UUIDs for {@code T} type lexica owned by the given owner.
 * @param em the {@link EntityManager} to use.
 * @param ownerId the ID of the owner./*  ww  w. j av  a2  s. com*/
 * @param entityClass the specific type of lexica to be retrieved; must be annotated with the {@link Entity} annotation.
 * @return a {@link List} containing {@link String} representations of the UUIDs.
 */
public <T extends Lexicon> List<String> getAllLexica(EntityManager em, String ownerId, Class<T> entityClass) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(ownerId, CannedMessages.NULL_ARGUMENT, "ownerId");
    Validate.notNull(entityClass, CannedMessages.NULL_ARGUMENT, "entityClass");

    TypedQuery<byte[]> query = em.createQuery("SELECT lex.id FROM Lexicon lex " + "WHERE lex.ownerId=:ownerId "
            + "AND TYPE(lex)=:type AND (lex.baseStore IS NULL "
            + "OR lex.baseStore IN (SELECT d FROM DocumentCorpus d))", byte[].class);
    query.setParameter("ownerId", ownerId).setParameter("type", entityClass);

    List<byte[]> results = query.getResultList();
    return Lists.newArrayList(Iterables.transform(results, UuidUtils.uuidBytesToStringFunction()));
}

From source file:edu.csueb.cs6320.utils.UserService.java

public List<User> getUserList() {
    EntityManager em = Persistence.createEntityManagerFactory("TestPU").createEntityManager();

    em.getTransaction().begin();/*from   w  w  w.  j a va  2 s  . c om*/
    List<User> users = em.createQuery("SELECT u FROM User u", User.class).getResultList();
    em.getTransaction().commit();
    em.close();

    return users;
}

From source file:nl.waisda.services.EuropeanaImportServiceTest.java

@Test
@Transactional//from ww  w  . j a  va  2 s.  c  o m
@Rollback(value = true)
public void testImportNoVideo() {
    HttpUriRequest overview = new HttpGet(
            "http://preview.europeana.eu/api/v2/search.json?wskey=XxxsEZoWj&query=dontcare&start=1&rows=12&profile=minimal");
    HttpUriRequest details = new HttpGet("http://detail");
    try {
        setup();
        // setup http response
        setupHttpResponse("http://www.host.com/image.png", "", "http://www.host.com/webresource.mov");
        // call the service
        service.importEuropeanaData("dontcare");
        EntityManager em = entityManager;//Factory.getObject().createEntityManager();
        TypedQuery q = em.createQuery("select v from Video v", Video.class);
        List<Video> result = q.getResultList();
        Assert.assertEquals(0, result.size());

    } catch (Exception e) {
        Assert.fail("Not supposed to fail");
        LOG.error(e);
    }
}

From source file:nl.waisda.services.EuropeanaImportServiceTest.java

@Test
@Transactional//  w w  w .jav a 2  s.  c o  m
@Rollback(value = true)
public void testImportAcceptMp4FromWebresource() {
    HttpUriRequest overview = new HttpGet(
            "http://preview.europeana.eu/api/v2/search.json?wskey=XxxsEZoWj&query=dontcare&start=1&rows=12&profile=minimal");
    HttpUriRequest details = new HttpGet("http://detail");
    try {
        setup();
        // setup http response
        setupHttpResponse("http://www.host.com/image.png", "", "http://www.host.com/webresource.mp4");
        // call the service
        service.importEuropeanaData("dontcare");
        EntityManager em = entityManager;//Factory.getObject().createEntityManager();
        TypedQuery q = em.createQuery("select v from Video v", Video.class);
        List<Video> result = q.getResultList();
        Assert.assertEquals(1, result.size());
        Assert.assertEquals("http://www.host.com/webresource.mp4", result.get(0).getSourceUrl());
        Assert.assertEquals("http://www.host.com/image.png", result.get(0).getImageUrl());

    } catch (Exception e) {
        Assert.fail("Not supposed to fail");
        LOG.error(e);
    }
}