Example usage for javax.persistence EntityManager getCriteriaBuilder

List of usage examples for javax.persistence EntityManager getCriteriaBuilder

Introduction

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

Prototype

public CriteriaBuilder getCriteriaBuilder();

Source Link

Document

Return an instance of CriteriaBuilder for the creation of CriteriaQuery objects.

Usage

From source file:de.egore911.persistence.selector.AbstractSelector.java

public long count() {
    EntityManager em = EntityManagerUtil.getEntityManager();
    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<T> from = cq.from(getEntityClass());
    List<Predicate> predicates = generatePredicateList(builder, from, cq);
    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    cq.select(builder.count(from));/*from  w ww.jav  a 2  s. c om*/
    TypedQuery<Long> q = em.createQuery(cq);
    return q.getSingleResult();
}

From source file:dao.jpa.TestJpaDao.java

@Test
@Transactional//from   w  w  w. j a  v  a 2  s. c  om
public void testCountCriteria() {
    EntityManager em = bookDao.getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Book> criteria = cb.createQuery(Book.class);

    Root<Book> root = criteria.from(Book.class);
    Join<Book, Author> join = root.join("author");
    criteria.where(join.isNotNull());

    CriteriaQuery<Long> countCriteria = JpaUtils.countCriteria(em, criteria);
    Long result = em.createQuery(countCriteria).getSingleResult();
    log.debug("Count: " + result);
}

From source file:org.seedstack.i18n.rest.internal.infrastructure.jpa.KeysQuery.java

public KeysQuery(EntityManager entityManager) {
    this.entityManager = entityManager;
    criteriaBuilder = entityManager.getCriteriaBuilder();
}

From source file:org.eclipse.jubula.client.core.persistence.NodePM.java

/**
 * Loads a bag of Nodes into the given session and returns the loaded
 * Nodes.//w  w  w.  j  a va2 s  .c  o m
 * 
 * @param projectId The Project in which to search for the Nodes.
 * @param guids The GUIDs for which to load Nodes.
 * @param session The session into which to load the Nodes.
 * @return the loaded Nodes, mapped by GUID. GUIDs for which no node could
 *         be found are mapped to <code>null</code>.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static synchronized Map<String, INodePO> getNodes(Long projectId, Collection<String> guids,
        EntityManager session) {

    CriteriaQuery query = session.getCriteriaBuilder().createQuery();
    Root from = query.from(NodeMaker.getNodePOClass());
    Predicate parentProjectPred = session.getCriteriaBuilder().equal(from.get("hbmParentProjectId"), projectId); //$NON-NLS-1$
    Predicate guidDisjunction = PersistenceUtil.getExpressionDisjunction(guids, from.get("guid"), //$NON-NLS-1$
            session.getCriteriaBuilder());
    query.select(from).where(parentProjectPred, guidDisjunction);

    List<INodePO> nodeList = session.createQuery(query).getResultList();

    Map<String, INodePO> guidToNodeMap = new HashMap<String, INodePO>();
    for (INodePO node : nodeList) {
        String guid = node.getGuid();
        if (!guidToNodeMap.containsKey(guid)) {
            guidToNodeMap.put(guid, node);
        }
    }

    return guidToNodeMap;
}

From source file:dao.jpa.TestJpaDao.java

@Test
@Transactional//from   w  w w  .  ja  v  a  2s. c  o  m
public void testCopy() {
    EntityManager em = bookDao.getEntityManager();
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Book> criteria = cb.createQuery(Book.class);

    // Fetch join
    Root<Book> root = criteria.from(Book.class);
    Path<String> path = root.join("author").<String>get("name");
    root.fetch("author");
    criteria.select(root);

    // SubQuery
    Subquery<String> sq = criteria.subquery(String.class);
    Root<Author> author = sq.from(Author.class);
    sq.select(author.<String>get("name"));
    sq.where(cb.equal(author.<String>get("name"), "Rod"));

    criteria.where(cb.in(path).value(sq));

    CriteriaQuery<Book> copy = cb.createQuery(Book.class);
    JpaUtils.copyCriteria(criteria, copy);

    List<Book> copyBooks = em.createQuery(copy).getResultList();
    List<Book> books = em.createQuery(criteria).getResultList();
    assertEquals(books, copyBooks);
}

From source file:controllers.AuthController.java

@UnitOfWork
@FilterWith(CTCheck.class)
public Result login(Context context, Session session, User req) {
    EntityManager entitymanager = entitiyManagerProvider.get();
    CriteriaBuilder cb = entitymanager.getCriteriaBuilder();

    try {//www.  java  2  s .  c om
        CriteriaQuery<User> query = cb.createQuery(User.class);
        Root<User> a = query.from(User.class);
        query.where(cb.equal(a.get(User_.email), req.getEmail()),
                cb.equal(a.get(User_.password), req.getPassword()));
        User u = entitymanager.createQuery(query).getSingleResult();
        String token = SessionIdentifierGenerator.nextSessionId();
        context.addCookie(Cookie.builder("token", token).build());
        session.put("token", token);
        session.put("email", u.getEmail());
        session.put("id", String.valueOf(u.getId()));
        ninjaCache.set(token, u.getId());
        return Results.json().render(new RespAuth(u.getId(), token, u.getEmail()));
    } catch (Exception e) {
        e.printStackTrace();
        return Results.json().status(400).render(new JSendResp(400, e));
    }
}

From source file:ispok.dao.TournamentHibernateJpaDao.java

@Override
public List<Tournament> getPage(int first, int rows, String sortBy, boolean ascending,
        Map<String, Object> filters) {

    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //        CriteriaBuilder cb = entityManagerfactory.getCriteriaBuilder();
    //        CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    //        Root<Tournament> tou = cq.from(Tournament.class);
    //        cb.para
    //        criteria.add(cb.equal(tou, tou))
    //        String queryString = "SELECT e FROM " + Tournament.class.getSimpleName();
    //        if (!filters.isEmpty()) {
    //            queryString += " WHERE ";
    //            for (Map.Entry<String, Object> entry : filters.entrySet()) {
    //                if ("id".equals(entry.getKey())) {
    //                    queryString += "e." + entry.getKey() + " = " + entry.getValue();
    //                } else {
    //                    queryString += "e." + entry.getKey() + " LIKE '" + entry.getValue() + "'";
    //                }
    //            }
    //        }//from  w ww. j  av a2 s. co m
    //                " e WHERE e." + property + " = :value";
    //        return getEntityManager().createQuery(queryString).setParameter("value", value).getResultList();
    //        return null;
    //        Session session = getEntityManager().unwrap(Session.class);
    //        Criteria criteria = session.createCriteria(Tournament.class);
    //
    //        for (Map.Entry<String, Object> filter : filters.entrySet()) {
    //            if ("id".equals(filter.getKey())) {
    //                criteria.add(Restrictions.eq("id", Long.parseLong(filter.getValue().toString())));
    //            } else {
    //                criteria.add(Restrictions.ilike(filter.getKey(), (String) filter.getValue(), MatchMode.START));
    //            }
    //        }
    //
    //        if (ascending) {
    //            criteria.addOrder(Order.asc(sortBy));
    //        } else {
    //            criteria.addOrder(Order.desc(sortBy));
    //        }
    //
    //        criteria.setFirstResult(first);
    //        criteria.setMaxResults(rows);
    //
    //        criteria.setResultTransformer(Transformers.aliasToBean(clazz));
    //        List<ENTITY> list = criteria.list();
    //
    //        return list;
    EntityManager em = getEntityManager();

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Tournament> cq = cb.createQuery(Tournament.class);
    Root<Tournament> t = cq.from(Tournament.class);

    cq.select(t);

    TypedQuery<Tournament> tq = em.createQuery(cq);

    List<Tournament> tournaments = tq.getResultList();
    return tournaments;

}

From source file:br.nom.abdon.gastoso.dal.FatosDao.java

public List<Fato> listar(final EntityManager em, final FiltroFatos filtroFatos) {

    final CriteriaBuilder cb = em.getCriteriaBuilder();

    final CriteriaQuery<Fato> q = cb.createQuery(Fato.class);

    final Root<Fato> root = q.from(Fato.class);

    final List<Predicate> where = new LinkedList<>();
    final Map<String, Object> params = new HashMap<>();

    buildQuery(cb, filtroFatos, root, where, params);

    trataOrdenacao(filtroFatos, root, cb, q);

    return DalUtil.prepareAndRunQuery(em, q, where, params, filtroFatos.getPaginacao());
}

From source file:org.eclipse.jubula.client.core.persistence.NodePM.java

/**
 * Finds a Test Suite within the currently opened project.
 * //from   w  w w  .j  a  va 2  s.com
 * @param testSuiteGuid The GUID of the Test Suite.
 * @return the Test Suite with the given GUID, or <code>null</code> if 
 *         no such Test Suite can be found.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static synchronized ITestSuitePO getTestSuite(String testSuiteGuid) {

    GeneralStorage gs = GeneralStorage.getInstance();
    IProjectPO currentProject = gs.getProject();
    if (currentProject != null) {
        EntityManager s = gs.getMasterSession();

        CriteriaBuilder builder = s.getCriteriaBuilder();
        CriteriaQuery query = builder.createQuery();
        Root from = query.from(NodeMaker.getTestSuitePOClass());
        query.select(from).where(builder.like(from.get("guid"), testSuiteGuid), //$NON-NLS-1$
                builder.equal(from.get("hbmParentProjectId"), currentProject.getId())); //$NON-NLS-1$

        try {
            Object result = s.createQuery(query).getSingleResult();
            if (result instanceof ITestSuitePO) {
                return (ITestSuitePO) result;
            }
        } catch (NoResultException nre) {
            // No result found. Fall through to return null as per javadoc.
        }
    }

    return null;
}

From source file:org.eclipse.jubula.client.core.persistence.NodePM.java

/**
 * @param type//from  w  w w .j a  va2s. com
 *            the type of elements to find
 * @param parentProjectId
 *            ID of the parent project to search in
 * @param s
 *            The session into which the INodePOs will be loaded.
 * @return list of param all INodePOs
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static List<? extends INodePO> computeListOfNodes(Class type, Long parentProjectId, EntityManager s) {
    Assert.isNotNull(type);
    Assert.isNotNull(s);
    CriteriaQuery query = s.getCriteriaBuilder().createQuery();
    Root from = query.from(type);
    query.select(from).where(s.getCriteriaBuilder().equal(from.get("hbmParentProjectId"), parentProjectId)); //$NON-NLS-1$

    List<INodePO> queryResult = s.createQuery(query).getResultList();
    return queryResult;
}