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:info.dolezel.jarss.rest.v1.FeedsService.java

private JsonObjectBuilder getFeed(EntityManager em, Feed feed) {
    JsonObjectBuilder objFeed = Json.createObjectBuilder();
    Date readAllBefore;//from www .j av  a 2  s. c o m

    if (feed.getReadAllBefore() != null)
        readAllBefore = feed.getReadAllBefore();
    else
        readAllBefore = new Date(0);

    long count = (Long) em.createQuery(
            "select count(*) from FeedItemData fid left outer join fid.feedItems as fi where fid.feedData = :fd and (fi is null or (fi.feed = :feed and fi.read = false)) and fid.date > :readAllBefore",
            Long.class).setParameter("fd", feed.getData()).setParameter("feed", feed)
            .setParameter("readAllBefore", readAllBefore).getSingleResult();

    objFeed.add("id", feed.getId());
    objFeed.add("title", feed.getName());
    objFeed.add("unread", count);
    objFeed.add("isCategory", false);

    Date lastFetch = feed.getData().getLastFetch();
    if (lastFetch != null)
        objFeed.add("lastFetchTime", lastFetch.getTime());

    String lastError = feed.getData().getLastError();
    if (lastError != null)
        objFeed.add("lastError", lastError);

    return objFeed;
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}//from   ww w  .  j  a  v  a  2s.  com
 */
@Override
public <T> T getScalarResultOfType(Class<T> resultClass, QueryType type, String query, List<Object> posParams) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        switch (type) {
        case JPA:
            TypedQuery<T> typedQuery = em.createQuery(query, resultClass);
            JpaUtil.bindQueryParams(typedQuery, posParams);
            return typedQuery.getSingleResult();
        case NATIVE:
            Query nativeQuery = em.createNativeQuery(query, resultClass);
            JpaUtil.bindQueryParams(nativeQuery, posParams);
            return resultClass.cast(nativeQuery.getSingleResult());
        default:
            throw new IllegalStateException("Invalid QueryType!!");
        }
    } catch (Exception ex) { // NOSONAR
        throw new JpaException(ex);
    } finally {
        JpaUtil.closeEntityManager(em);
    }
}

From source file:info.dolezel.jarss.rest.v1.FeedsService.java

@DELETE
@Path("{id}")
public Response unsubscribeFeed(@Context SecurityContext context, @PathParam("id") int feedId) {
    EntityManager em;
    EntityTransaction tx;//from   w ww.ja  v a2  s  . co  m
    User user;
    Feed f;
    FeedData fd;

    em = HibernateUtil.getEntityManager();
    tx = em.getTransaction();
    user = (User) context.getUserPrincipal();

    try {
        tx.begin();

        try {
            f = (Feed) em.createQuery("from Feed where id = :id", Feed.class).setParameter("id", feedId)
                    .getSingleResult();
        } catch (NoResultException e) {
            return Response.status(Response.Status.NOT_FOUND)
                    .entity(new ErrorDescription("Feed does not exist")).build();
        }
        if (!f.getUser().equals(user)) {
            return Response.status(Response.Status.FORBIDDEN)
                    .entity(new ErrorDescription("Feed not owned by user")).build();
        }

        fd = f.getData();
        em.remove(f);

        if (fd.getFeeds().isEmpty())
            em.remove(fd);

        tx.commit();

        return Response.noContent().build();
    } finally {
        if (tx.isActive())
            tx.rollback();
        em.close();
    }
}

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

/**
 * Get a list of ingredients.// ww w. j  av  a2s  .com
 * @param _groupId The id of the group containing various ingredients.
 * @param _changedSince Limits the result 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 getIngredients(@PathParam("groupid") int _groupId,
        @QueryParam("changedsince") String _changedSince) throws Exception {
    List<Ingredient> ingedients;
    List<DeletedObject> deletedIngredients;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

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

        TypedQuery<Ingredient> IngredientsQuery = manager.createQuery(
                "select i from " + "Ingredient i where i.group = :group and i.updated > :updated",
                Ingredient.class);
        IngredientsQuery.setParameter("group", group);
        IngredientsQuery.setParameter("updated", changedSince);
        ingedients = IngredientsQuery.getResultList();

        TypedQuery<DeletedObject> deletedIngredientsQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        deletedIngredientsQuery.setParameter("group", group);
        deletedIngredientsQuery.setParameter("updated", changedSince);
        deletedIngredientsQuery.setParameter("type", DeletedObject.Type.INGREDIENT);
        deletedIngredients = deletedIngredientsQuery.getResultList();
    } else {
        ingedients = new ArrayList<Ingredient>(group.getIngredients());

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

    ArrayList<IngredientInfo> rtn = new ArrayList<IngredientInfo>(
            ingedients.size() + deletedIngredients.size());
    for (Ingredient current : ingedients) {
        IngredientInfo toAdd = new IngredientInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setProductUUID(current.getProduct().getUUID());
        toAdd.setRecipeUUID(current.getRecipe().getUUID());
        toAdd.setAmount(current.getAmount());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : deletedIngredients) {
        IngredientInfo toAdd = new IngredientInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Get a list of shopping-lists./* w  ww . j a v  a2  s  .  c o  m*/
 * @param _groupId The id of the group, containing the lists.
 * @param _changedSince Requests only the elements that changed since the given date. ISO 8601
 *                     time e.g. 2016-01-19T11:54:07+0100
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getLists(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {

    List<ShoppingList> foundLists;
    List<DeletedObject> foundDeleted;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

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

        TypedQuery<ShoppingList> foundListsQuery = manager.createQuery(
                "select sl from " + "ShoppingList sl where sl.group = :group and sl.updated > :updated",
                ShoppingList.class);
        foundListsQuery.setParameter("group", group);
        foundListsQuery.setParameter("updated", changedSince);
        foundLists = foundListsQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedListsQuery = manager
                .createQuery("select do from" + " DeletedObject do where do.group = :group and "
                        + "do.updated > :updated and do.type = :type", DeletedObject.class);
        foundDeletedListsQuery.setParameter("group", group);
        foundDeletedListsQuery.setParameter("updated", changedSince);
        foundDeletedListsQuery.setParameter("type", DeletedObject.Type.LIST);
        foundDeleted = foundDeletedListsQuery.getResultList();
    } else {
        TypedQuery<ShoppingList> foundListsQuery = manager
                .createQuery("select sl from " + "ShoppingList sl where sl.group = :group", ShoppingList.class);
        foundListsQuery.setParameter("group", group);
        foundLists = foundListsQuery.getResultList();

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

    ArrayList<ListInfo> rtn = new ArrayList<ListInfo>(foundLists.size() + foundDeleted.size());
    for (ShoppingList current : foundLists) {
        ListInfo toAdd = new ListInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        if (current.getCategory() != null)
            toAdd.setCategoryUUID(current.getCategory().getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(false);
        rtn.add(toAdd);
    }
    for (DeletedObject current : foundDeleted) {
        ListInfo toAdd = new ListInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Get a list of tagged products./*from  w  w w  . ja va 2s  . com*/
 * @param _groupId The id of the group containing various tagged products.
 * @param _changedSince Limits the result 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 getTaggedProducts(@PathParam("groupid") int _groupId,
        @QueryParam("changedsince") String _changedSince) throws Exception {
    List<TaggedProduct> taggedProducts;
    List<DeletedObject> deletedTaggedProducts;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

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

        TypedQuery<TaggedProduct> taggedProductQuery = manager.createQuery(
                "select tp from " + "TaggedProduct tp where tp.group = :group and tp.updated > :updated",
                TaggedProduct.class);
        taggedProductQuery.setParameter("group", group);
        taggedProductQuery.setParameter("updated", changedSince);
        taggedProducts = taggedProductQuery.getResultList();

        TypedQuery<DeletedObject> deletedTaggedProductQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        deletedTaggedProductQuery.setParameter("group", group);
        deletedTaggedProductQuery.setParameter("updated", changedSince);
        deletedTaggedProductQuery.setParameter("type", DeletedObject.Type.TAGGEDPRODUCT);
        deletedTaggedProducts = deletedTaggedProductQuery.getResultList();
    } else {
        taggedProducts = new ArrayList<TaggedProduct>(group.getTaggedProducts());

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

    ArrayList<TaggedProductInfo> rtn = new ArrayList<TaggedProductInfo>(
            taggedProducts.size() + deletedTaggedProducts.size());
    for (TaggedProduct current : taggedProducts) {
        TaggedProductInfo toAdd = new TaggedProductInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setProductUUID(current.getProduct().getUUID());
        toAdd.setTagUUID(current.getTag().getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : deletedTaggedProducts) {
        TaggedProductInfo toAdd = new TaggedProductInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Get a list of listEntries.//from ww w . j ava 2  s  .  com
 * @param _groupId The id of the group containing various list-entries.
 * @param _changedSince Limits the result to elements that changed since the given date. ISO
 *                      8601 time e.g. 2016-01-19T11:54:07+0100
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getEntries(@PathParam("groupid") int _groupId, @QueryParam("changedsince") String _changedSince)
        throws Exception {
    List<ListEntry> foundEntries;
    List<DeletedObject> foundDeleted;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

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

        TypedQuery<ListEntry> foundEntriesQuery = manager.createQuery(
                "select le from " + "ListEntry le where le.group = :group and le.updated > :updated",
                ListEntry.class);
        foundEntriesQuery.setParameter("group", group);
        foundEntriesQuery.setParameter("updated", changedSince);
        foundEntries = foundEntriesQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedEntriesQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and "
                        + "do.type = :type",
                DeletedObject.class);
        foundDeletedEntriesQuery.setParameter("group", group);
        foundDeletedEntriesQuery.setParameter("updated", changedSince);
        foundDeletedEntriesQuery.setParameter("type", DeletedObject.Type.LISTENTRY);
        foundDeleted = foundDeletedEntriesQuery.getResultList();
    } else {
        foundEntries = new ArrayList<ListEntry>(group.getListEntries());

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

    ArrayList<EntryInfo> rtn = new ArrayList<EntryInfo>(foundEntries.size() + foundDeleted.size());
    for (ListEntry current : foundEntries) {
        EntryInfo toAdd = new EntryInfo().withDeleted(false);
        toAdd.setUUID(current.getUUID());
        toAdd.setProductUUID(current.getProduct().getUUID());
        toAdd.setListUUID(current.getList().getUUID());
        toAdd.setAmount(current.getAmount());
        toAdd.setPriority(current.getPriority());
        toAdd.setStruck(current.getStruck());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        rtn.add(toAdd);
    }
    for (DeletedObject current : foundDeleted) {
        EntryInfo toAdd = new EntryInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

/**
 * Get a list of products./* ww  w.  ja v a  2 s.c o  m*/
 * @param _groupId The id of the group containing the products.
 * @param _changedSince Optional. Limits the request to the elements that changed since the
 *                      given date. ISO 8601 time e.g. "2016-01-19T11:54:07+0100".
 */
@GET
@TokenSecured
@Produces({ "application/json" })
public Response getProducts(@PathParam("groupid") int _groupId,
        @QueryParam("changedsince") String _changedSince) throws Exception {
    List<Product> foundProducts;
    List<DeletedObject> foundDeleted;
    EntityManager manager = DatabaseHelper.getInstance().getManager();
    DeviceGroup group = manager.find(DeviceGroup.class, _groupId);

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

        TypedQuery<Product> foundProductsQuery = manager.createQuery(
                "select p from " + "Product p where p.group = :group and p.updated > :updated", Product.class);
        foundProductsQuery.setParameter("group", group);
        foundProductsQuery.setParameter("updated", changedSince);
        foundProducts = foundProductsQuery.getResultList();

        TypedQuery<DeletedObject> foundDeletedListsQuery = manager.createQuery(
                "select do " + "from DeletedObject do where do.group = :group and do.updated > :updated and"
                        + " do.type = :type",
                DeletedObject.class);
        foundDeletedListsQuery.setParameter("group", group);
        foundDeletedListsQuery.setParameter("updated", changedSince);
        foundDeletedListsQuery.setParameter("type", DeletedObject.Type.PRODUCT);
        foundDeleted = foundDeletedListsQuery.getResultList();
    } else {
        TypedQuery<Product> foundProductsQuery = manager
                .createQuery("select p from " + "Product p where p.group = :group", Product.class);
        foundProductsQuery.setParameter("group", group);
        foundProducts = foundProductsQuery.getResultList();

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

    ArrayList<ProductInfo> rtn = new ArrayList<ProductInfo>(foundProducts.size() + foundDeleted.size());
    for (Product current : foundProducts) {
        ProductInfo toAdd = new ProductInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setName(current.getName());
        toAdd.setDefaultAmount(current.getDefaultAmount());
        toAdd.setStepAmount(current.getStepAmount());
        if (current.getUnit() != null)
            toAdd.setUnitUUID(current.getUnit().getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(false);
        rtn.add(toAdd);
    }
    for (DeletedObject current : foundDeleted) {
        ProductInfo toAdd = new ProductInfo();
        toAdd.setUUID(current.getUUID());
        toAdd.setLastChanged(Date.from(current.getUpdated()));
        toAdd.setDeleted(true);
        rtn.add(toAdd);
    }

    return ResponseFactory.generateOK(rtn);
}

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

@Test
public void testInsert() {
    EntityManager em = emf.createEntityManager();
    PrintedBookDAOImpl bdao = new PrintedBookDAOImpl();
    bdao.setManager(em);/*from  w ww  .j ava  2 s. c o m*/

    em.getTransaction().begin();

    Book book = new Book();
    book.setName("Harry Potter");
    book.setISBN("123112315");
    book.setDescription("Book about Wizard!");
    book.setAuthors("J.K. Rowling");
    book.setDepartment(Department.Sport);
    book.setIdBook(1);

    PrintedBook pbook = new PrintedBook();
    pbook.setBook(book);
    pbook.setState(Boolean.FALSE);
    pbook.setCondition(Condition.Damaged);
    bdao.insert(pbook);

    em.getTransaction().commit();

    List<PrintedBook> books = em.createQuery("SELECT b FROM PrintedBook b", PrintedBook.class).getResultList();

    em.close();
    assertEquals(books.size(), 3);
}

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

@Test
public void testDelete() {
    EntityManager em = emf.createEntityManager();
    PrintedBookDAOImpl bdao = new PrintedBookDAOImpl();
    bdao.setManager(em);/*from  www. j  av  a  2  s .  c o  m*/
    em.getTransaction().begin();

    Book book = new Book();
    book.setName("Harry Potter");
    book.setISBN("123112315");
    book.setDescription("Book about Wizard!");
    book.setAuthors("J.K. Rowling");
    book.setDepartment(Department.Sport);
    book.setIdBook(1);

    PrintedBook pbook = new PrintedBook();
    pbook.setBook(book);
    pbook.setState(Boolean.FALSE);
    pbook.setCondition(Condition.New);
    pbook.setIdPrintedBook(1);

    bdao.delete(pbook);
    em.getTransaction().commit();
    List<PrintedBook> books = em.createQuery("SELECT b FROM PrintedBook b", PrintedBook.class).getResultList();

    em.close();
    assertEquals(books.size(), 1);
}