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 all relevant set covers.//w  w  w .j  a va 2s  .co m
 * @param em the {@link EntityManager} to use.
 * @param ownerId the ID of the owner.
 * @param baseCorpus the {@link DocumentCorpus} which is the base corpus for the set cover.
 * @param entityClass the specific type of set covers 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 DocumentSetCover> List<String> getAllSetCovers(EntityManager em, String ownerId,
        DocumentCorpus baseCorpus, Class<T> entityClass) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(ownerId, CannedMessages.NULL_ARGUMENT, "ownerId");
    Validate.notNull(baseCorpus, CannedMessages.NULL_ARGUMENT, "baseCorpus");
    Validate.notNull(entityClass, CannedMessages.NULL_ARGUMENT, "entityClass");

    TypedQuery<byte[]> query = em.createQuery("SELECT sc.id FROM DocumentSetCover sc "
            + "WHERE sc.ownerId=:ownerId " + "AND TYPE(sc)=:type " + "AND sc.baseStore=:baseCorpus",
            byte[].class);
    query.setParameter("ownerId", ownerId).setParameter("type", entityClass).setParameter("baseCorpus",
            baseCorpus);

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

From source file:org.noorganization.instalist.server.api.CategoriesResource.java

/**
 * Get a list of categories./*from  ww w  . ja  v  a 2 s . co m*/
 *
 * @param _groupId The id of the group.
 * @param _categoryUUID The uuid of the category to fetch.
 */
@GET
@TokenSecured
@Path("{categoryuuid}")
@Produces({ "application/json" })
public Response getCategory(@PathParam("groupid") int _groupId, @PathParam("categoryuuid") String _categoryUUID)
        throws Exception {
    UUID categoryUUID;
    try {
        categoryUUID = UUID.fromString(_categoryUUID);
    } catch (IllegalArgumentException e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_UUID);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    TypedQuery<Category> categoriesQuery = manager.createQuery(
            "select c from Category c " + "where c.group = :groupid and c.UUID = :uuid", Category.class);
    categoriesQuery.setParameter("groupid", group);
    categoriesQuery.setParameter("uuid", categoryUUID);
    List<Category> categories = categoriesQuery.getResultList();
    if (categories.size() != 1) {
        TypedQuery<DeletedObject> deletedCategoriesQuery = manager
                .createQuery("select do " + "from DeletedObject do where do.group = :groupid and "
                        + "do.type = :type and do.UUID = :uuid", DeletedObject.class);
        deletedCategoriesQuery.setParameter("groupid", group);
        deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY);
        deletedCategoriesQuery.setParameter("uuid", categoryUUID);
        List<DeletedObject> deletedCategories = deletedCategoriesQuery.getResultList();
        manager.close();
        if (deletedCategories.size() == 1) {
            CategoryInfo catInfo = new CategoryInfo();
            catInfo.setDeleted(true);
            catInfo.setLastChanged(Date.from(deletedCategories.get(0).getUpdated()));
            catInfo.setUUID(categoryUUID);
            return ResponseFactory.generateGone(catInfo);
        } else {
            return ResponseFactory.generateNotFound(new Error().withMessage("Category was not" + " found."));
        }
    }
    manager.close();
    CategoryInfo catInfo = new CategoryInfo();
    catInfo.setDeleted(false);
    catInfo.setLastChanged(Date.from(categories.get(0).getUpdated()));
    catInfo.setName(categories.get(0).getName());
    catInfo.setUUID(categoryUUID);

    return ResponseFactory.generateOK(catInfo);
}

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

/**
 * Finds the builder associated with a given corpus and lexicon.
 * @param em the {@link EntityManager} to use.
 * @param corpus the {@link DocumentCorpus} being used to build the lexicon.
 * @param lexicon the {@link Lexicon} being built.
 * @return the {@link LexiconBuilderDocumentStore} object found, if any; {@code null} otherwise.
 *///www  . jav a2 s .c om
public LexiconBuilderDocumentStore findBuilder(EntityManager em, DocumentCorpus corpus, Lexicon lexicon) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(corpus, CannedMessages.NULL_ARGUMENT, "corpus");
    Validate.notNull(lexicon, CannedMessages.NULL_ARGUMENT, "lexicon");

    TypedQuery<LexiconBuilderDocumentStore> query = em.createQuery(
            "SELECT b FROM LexiconBuilderDocumentStore b "
                    + "WHERE b.baseStore=:corpus AND :lexicon MEMBER OF b.referencedObjects",
            LexiconBuilderDocumentStore.class);
    query.setMaxResults(1).setParameter("corpus", corpus).setParameter("lexicon", lexicon);

    return this.getSingleResult(query);
}

From source file:org.noorganization.instalist.server.api.TagResource.java

/**
 * Get a list of tags./*  ww w. j  a  v  a  2s . co  m*/
 * @param _groupId The id of the group containing the tags.
 * @param _changedSince Limits the request to elements that changed since the given date. ISO
 *                      8601 time e.g. 2016-01-19T11:54:07+0100. Optional.
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getTags(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    Instant changedSince = null;
    try {
        if (_changedSince != null)
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
    } catch (ParseException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    List<Tag> tags;
    List<DeletedObject> deletedTags;
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (changedSince != null) {
        TypedQuery<Tag> tagQuery = manager.createQuery(
                "select t from Tag t where " + "t.group = :group and t.updated > :updated", Tag.class);
        tagQuery.setParameter("group", group);
        tagQuery.setParameter("updated", changedSince);
        tags = tagQuery.getResultList();

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("updated", changedSince);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG);
        deletedTags = deletedRecipesQuery.getResultList();
    } else {
        tags = new ArrayList<Tag>(group.getTags());

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.TAG);
        deletedTags = deletedRecipesQuery.getResultList();
    }
    manager.close();

    ArrayList<TagInfo> rtn = new ArrayList<TagInfo>(tags.size() + deletedTags.size());
    for (Tag current : tags) {
        TagInfo toAdd = new TagInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : deletedTags) {
        TagInfo toAdd = new TagInfo().withDeleted(true);
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Refreshes the state of the given builder based on its base corpus and adds any missing documents.
 * @param em the {@link EntityManager} to use.
 * @param builder the {@link LexiconBuilderDocumentStore} to refresh.
 * @return the supplied {@link LexiconBuilderDocumentStore} object.
 *//*  ww  w  .  j  a  v a2 s. c  o  m*/
public LexiconBuilderDocumentStore refreshBuilder(EntityManager em, LexiconBuilderDocumentStore builder) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");
    Validate.notNull(builder, CannedMessages.NULL_ARGUMENT, "builder");
    Validate.notNull(builder.getCorpus(), CannedMessages.NULL_ARGUMENT, "builder.corpus");

    TypedQuery<FullTextDocument> ftdQuery = em.createQuery("SELECT d FROM FullTextDocument d "
            + "WHERE d.store=:corpus "
            + "AND NOT EXISTS (SELECT bd FROM LexiconBuilderDocument bd WHERE bd.store=:builder AND bd.baseDocument=d)",
            FullTextDocument.class);

    ftdQuery.setParameter("corpus", builder.getCorpus()).setParameter("builder", builder);

    for (FullTextDocument document : ftdQuery.getResultList()) {
        LexiconBuilderDocument lbd = new LexiconBuilderDocument(document);
        builder.addDocument(lbd);
        em.persist(lbd);
    }
    return builder;
}

From source file:org.noorganization.instalist.server.api.CategoriesResource.java

/**
 * Get a list of categories.//from  www  .ja  va  2 s. co  m
 *
 * @param _groupId The id of the group.
 * @param _changedSince Optional. Requests only the elements that changed since the given date.
 *                      ISO 8601 time e.g. 2016-01-19T11:54:07+01:00
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getCategories(@PathParam("groupid") int _groupId,
        @QueryParam("changedsince") String _changedSince) throws Exception {
    try {

        Instant changedSince = null;
        if (_changedSince != null) {
            try {
                changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
            } catch (ParseException _e) {
                return ResponseFactory.generateBadRequest(CommonEntity.INVALID_DATA);
            }
        }

        List<Category> categories;
        List<DeletedObject> deletedCategories;
        EntityManager manager = DatabaseHelper.getInstance().getManager();
        DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

        if (changedSince != null) {
            TypedQuery<Category> categoriesQuery = manager.createQuery(
                    "select c from Category c " + "where c.group = :groupid and c.updated > :updated",
                    Category.class);
            categoriesQuery.setParameter("groupid", group);
            categoriesQuery.setParameter("updated", changedSince);
            categories = categoriesQuery.getResultList();

            TypedQuery<DeletedObject> deletedCategoriesQuery = manager
                    .createQuery("select do " + "from DeletedObject do where do.group = :groupid and "
                            + "do.type = :type and do.updated > :updated", DeletedObject.class);
            deletedCategoriesQuery.setParameter("groupid", group);
            deletedCategoriesQuery.setParameter("updated", changedSince);
            deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY);
            deletedCategories = deletedCategoriesQuery.getResultList();
        } else {
            TypedQuery<Category> categoriesQuery = manager
                    .createQuery("select c from Category c " + "where c.group = :groupid", Category.class);
            categoriesQuery.setParameter("groupid", group);
            categories = categoriesQuery.getResultList();

            TypedQuery<DeletedObject> deletedCategoriesQuery = manager.createQuery(
                    "select do " + "from DeletedObject do where do.group = :groupid and " + "do.type = :type",
                    DeletedObject.class);
            deletedCategoriesQuery.setParameter("groupid", group);
            deletedCategoriesQuery.setParameter("type", DeletedObject.Type.CATEGORY);
            deletedCategories = deletedCategoriesQuery.getResultList();
        }
        manager.close();

        List<CategoryInfo> rtnPayload = new ArrayList<CategoryInfo>(
                categories.size() + deletedCategories.size());
        for (Category currentCat : categories) {
            CategoryInfo info = new CategoryInfo();
            info.setUUID(currentCat.getUUID());
            info.setName(currentCat.getName());
            info.setLastChanged(Date.from(currentCat.getUpdated()));
            info.setDeleted(false);
            rtnPayload.add(info);
        }
        for (DeletedObject currentCat : deletedCategories) {
            CategoryInfo info = new CategoryInfo();
            info.setUUID(currentCat.getUUID());
            info.setLastChanged(Date.from(currentCat.getUpdated()));
            info.setDeleted(true);
            rtnPayload.add(info);
        }

        return ResponseFactory.generateOK(rtnPayload);
    } catch (Exception _e) {
        _e.printStackTrace();
        throw _e;
    }
}

From source file:au.edu.uq.cmm.paul.grabber.Analyser.java

private SortedSet<DatasetMetadata> buildInDatabaseMetadata() {
    TreeSet<DatasetMetadata> inDatabase = new TreeSet<DatasetMetadata>(ORDER_BY_BASE_PATH_AND_TIME_AND_ID);
    EntityManager em = emf.createEntityManager();
    try {//from   w ww  .ja v a 2  s.c o m
        TypedQuery<DatasetMetadata> query = em.createQuery(
                "from DatasetMetadata m left join fetch m.datafiles " + "where m.facilityName = :name",
                DatasetMetadata.class);
        query.setParameter("name", getFacility().getFacilityName());
        for (DatasetMetadata ds : query.getResultList()) {
            if (inDatabase.add(ds)) {
                ds.getDatafiles().size();
            }
        }
    } finally {
        em.close();
    }
    return inDatabase;
}

From source file:org.noorganization.instalist.server.api.RecipeResource.java

/**
 * Get a list of recipes.//www.  j  av a2 s . co m
 * @param _groupId The id of the group containing the recipes.
 * @param _changedSince Limits the request to elements that changed since the given date. ISO
 *                      8601 time e.g. 2016-01-19T11:54:07+0100. Optional.
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getRecipes(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    Instant changedSince = null;
    try {
        if (_changedSince != null)
            changedSince = ISO8601Utils.parse(_changedSince, new ParsePosition(0)).toInstant();
    } catch (ParseException _e) {
        return ResponseFactory.generateBadRequest(CommonEntity.INVALID_CHANGEDATE);
    }

    EntityManager manager = DatabaseHelper.getInstance().getManager();
    List<Recipe> recipes;
    List<DeletedObject> deletedRecipes;
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

    if (changedSince != null) {
        TypedQuery<Recipe> recipeQuery = manager.createQuery(
                "select r from Recipe r where " + "r.group = :group and r.updated > :updated", Recipe.class);
        recipeQuery.setParameter("group", group);
        recipeQuery.setParameter("updated", changedSince);
        recipes = recipeQuery.getResultList();

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("updated", changedSince);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.RECIPE);
        deletedRecipes = deletedRecipesQuery.getResultList();
    } else {
        recipes = new ArrayList<Recipe>(group.getRecipes());

        TypedQuery<DeletedObject> deletedRecipesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.type = :type",
                DeletedObject.class);
        deletedRecipesQuery.setParameter("group", group);
        deletedRecipesQuery.setParameter("type", DeletedObject.Type.RECIPE);
        deletedRecipes = deletedRecipesQuery.getResultList();
    }
    manager.close();

    ArrayList<RecipeInfo> rtn = new ArrayList<RecipeInfo>(recipes.size() + deletedRecipes.size());
    for (Recipe current : recipes) {
        RecipeInfo toAdd = new RecipeInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : deletedRecipes) {
        RecipeInfo toAdd = new RecipeInfo().withDeleted(true);
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

@Test
public void testInsert() {

    EntityManager em = emf.createEntityManager();
    BookDAOImpl bdao = new BookDAOImpl();
    bdao.setManager(em);//w ww .  j a  v  a2  s . c o m

    Book book = new Book();
    book.setAuthors("Author");
    book.setDepartment(Department.Sport);
    book.setDescription("Description");
    book.setISBN("123456456");
    book.setName("Name");

    em.getTransaction().begin();

    bdao.insert(book);
    em.getTransaction().commit();
    List<Book> books = em.createQuery("SELECT b FROM Book b", Book.class).getResultList();
    em.close();
    assertEquals(books.size(), 2);
}

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

public static TypedQuery<PosteCandidature> findPostesCandidaturesByPostesAndCandidatAndRecevableAndAuditionnableAndModification(
        List<PosteAPourvoir> postes, List<User> candidats, List<ReviewStatusTypes> reviewStatus,
        Boolean recevable, Boolean auditionnable, Boolean modification, String sortFieldName,
        String sortOrder) {//from   w w  w. j a  v a  2  s  .  c o m
    EntityManager em = entityManager();
    String jpaQuery = "SELECT o FROM PosteCandidature AS o WHERE";
    if (postes != null) {
        jpaQuery = jpaQuery + " o.poste IN :postes AND";
    }
    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";
    if (fieldNames4OrderClauseFilter.contains(sortFieldName)) {
        jpaQuery = jpaQuery + " ORDER BY " + sortFieldName;
        if ("ASC".equalsIgnoreCase(sortOrder) || "DESC".equalsIgnoreCase(sortOrder)) {
            jpaQuery = jpaQuery + " " + sortOrder;
        }
    }
    TypedQuery<PosteCandidature> q = em.createQuery(jpaQuery, PosteCandidature.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 q;
}