Example usage for javax.persistence.criteria CriteriaBuilder equal

List of usage examples for javax.persistence.criteria CriteriaBuilder equal

Introduction

In this page you can find the example usage for javax.persistence.criteria CriteriaBuilder equal.

Prototype

Predicate equal(Expression<?> x, Object y);

Source Link

Document

Create a predicate for testing the arguments for equality.

Usage

From source file:com.expressui.sample.dao.query.RelatedOpportunitiesQuery.java

@Override
public List<Predicate> buildCriteria(CriteriaBuilder builder, CriteriaQuery<Opportunity> query,
        Root<Opportunity> opportunity) {
    List<Predicate> predicates = new ArrayList<Predicate>();

    if (hasValue(account)) {
        ParameterExpression<Account> accountExp = builder.parameter(Account.class, "account");
        predicates.add(builder.equal(opportunity.get("account"), accountExp));
    }// w  w w. j  a  va  2s .  c  om

    return predicates;
}

From source file:com.expressui.core.dao.security.query.RelatedUsersQuery.java

@Override
public List<Predicate> buildCriteria(CriteriaBuilder builder, CriteriaQuery<User> query, Root<User> user) {
    List<Predicate> predicates = new ArrayList<Predicate>();

    if (hasValue(role)) {
        ParameterExpression<Role> roleExp = builder.parameter(Role.class, "role");
        predicates.add(builder.equal(user.join("userRoles").get("role"), roleExp));
    }//  ww w  . j a v a 2  s. co  m

    if (hasValue(doesNotBelongToRole)) {
        Subquery<User> subquery = query.subquery(User.class);
        Root userRole = subquery.from(UserRole.class);
        ParameterExpression<Role> roleExp = builder.parameter(Role.class, "doesNotBelongToRole");
        subquery.select(userRole.get("user")).where(builder.equal(userRole.get("role"), roleExp));
        predicates.add(builder.not(user.in(subquery)));
    }

    return predicates;
}

From source file:core.commonapp.server.dao.security.SecurityGroupDaoHibernateImpl.java

@Override
@Transactional/*w  ww. ja  v a  2 s .  co m*/
public Set<SecurityGroup> findAllByUserLogin(UserLogin userLogin) {
    CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<SecurityGroup> query = builder.createQuery(SecurityGroup.class);

    Root<SecurityGroup> root = query.from(SecurityGroup.class);
    Join<SecurityGroup, UserLoginSecurityGroup> join = root.join("userLoginSecurityGroup");

    builder.equal(join.get("userLogin.userLoginId"), userLogin.getUserLoginId());
    builder.isNull(join.get("thruDate"));

    //        criteria.setFetchMode("userLoginSecurityGroups", FetchMode.SELECT);
    //        criteria.setFetchMode("permissionSecurityGroups", FetchMode.SELECT);

    Set<SecurityGroup> securityGroups = new HashSet<SecurityGroup>(
            getEntityManager().createQuery(query).getResultList());

    for (SecurityGroup securityGroup : securityGroups) {
        securityGroup.getPermissionSecurityGroups().size();
        securityGroup.getUserLoginSecurityGroups().size();
    }

    return securityGroups;
}

From source file:com.qpark.eip.core.spring.auth.dao.AuthorityDao.java

/**
 * Get the granted number of calls./*from   ww w  .  ja v a  2 s .  c  om*/
 *
 * @param userName
 *            the user name.
 * @param serviceName
 *            the service name.
 * @param operationName
 *            the operation name.
 * @return the number of calls.
 */
@Transactional(value = EipPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public int getGrantedRequestNumber(final String userName, final String serviceName,
        final String operationName) {
    Integer requests = 0;
    CriteriaBuilder cb = this.em.getCriteriaBuilder();
    CriteriaQuery<AuthenticationType> q = cb.createQuery(AuthenticationType.class);
    Root<AuthenticationType> c = q.from(AuthenticationType.class);
    q.where(cb.equal(c.<String>get(AuthenticationType_.context), this.contextNameProvider.getContextName()),
            cb.equal(c.<String>get(AuthenticationType_.userName), userName));

    TypedQuery<AuthenticationType> typedQuery = this.em.createQuery(q);
    try {
        AuthenticationType log = typedQuery.getSingleResult();
        for (GrantedAuthorityType role : log.getGrantedAuthority()) {
            if (this.getRoleName(serviceName, operationName).equals(role.getRoleName())) {
                requests = role.getMaxRequests();
            }
        }
        if (requests == null) {
            requests = Integer.MAX_VALUE;
        }
    } catch (Exception e) {
        requests = 0;
    }
    return requests;
}

From source file:br.ufba.dcc.mestrado.computacao.repository.impl.LicenseRepositoryImpl.java

@Override
public OpenHubLicenseEntity findByName(String name) {
    CriteriaBuilder criteriaBuilder = getEntityManager().getCriteriaBuilder();
    CriteriaQuery<OpenHubLicenseEntity> criteriaQuery = criteriaBuilder.createQuery(getEntityClass());

    Root<OpenHubLicenseEntity> root = criteriaQuery.from(getEntityClass());
    CriteriaQuery<OpenHubLicenseEntity> select = criteriaQuery.select(root);

    Predicate namePredicate = criteriaBuilder.equal(root.get("name"), name);
    select.where(namePredicate);/*from w ww  .  ja  va2s  .  c om*/

    TypedQuery<OpenHubLicenseEntity> query = getEntityManager().createQuery(criteriaQuery);

    OpenHubLicenseEntity result = null;

    try {
        result = query.getSingleResult();
    } catch (NoResultException ex) {

    } catch (NonUniqueResultException ex) {

    }

    return result;
}

From source file:se.kth.csc.persist.JPAStore.java

@Override
public Queue fetchQueueWithName(String name) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Queue> q = cb.createQuery(Queue.class);
    Root<Queue> queue = q.from(Queue.class);
    try {// w ww  . j  av  a2  s  .  c  o m
        return entityManager.createQuery(q.select(queue).where(cb.equal(queue.get(Queue_.name), name)))
                .getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

From source file:com.netflix.genie.server.metrics.impl.JobCountManagerImpl.java

/**
 * {@inheritDoc}/*ww  w.  j  a v a 2  s. c  o m*/
 */
@Override
@Transactional(readOnly = true)
//TODO: Move to specification
public int getNumInstanceJobs(final String hostName, final Long minStartTime, final Long maxStartTime)
        throws GenieException {
    LOG.debug("called");

    final String finalHostName;
    // initialize host name
    if (StringUtils.isBlank(hostName)) {
        finalHostName = NetUtil.getHostName();
    } else {
        finalHostName = hostName;
    }
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    final Root<Job> j = cq.from(Job.class);
    cq.select(cb.count(j));
    final Predicate runningStatus = cb.equal(j.get(Job_.status), JobStatus.RUNNING);
    final Predicate initStatus = cb.equal(j.get(Job_.status), JobStatus.INIT);
    final List<Predicate> predicates = new ArrayList<>();
    predicates.add(cb.equal(j.get(Job_.hostName), finalHostName));
    predicates.add(cb.or(runningStatus, initStatus));
    if (minStartTime != null) {
        predicates.add(cb.greaterThanOrEqualTo(j.get(Job_.started), new Date(minStartTime)));
    }
    if (maxStartTime != null) {
        predicates.add(cb.lessThan(j.get(Job_.started), new Date(maxStartTime)));
    }
    //documentation says that by default predicate array is conjuncted together
    cq.where(predicates.toArray(new Predicate[predicates.size()]));
    final TypedQuery<Long> query = this.em.createQuery(cq);
    //Downgrading to an int since all the code seems to want ints
    //Don't feel like changing everthing right now can figure out later
    //if need be
    return query.getSingleResult().intValue();
}

From source file:ru.portal.services.TableServiceImpl.java

/**
 * TODO    ManyToMany//  www  .  j av a 2  s. com
 * @param entityClass
 * @param id
 * @return 
 */
@Override
public Map<EntityType<?>, Map<String, String>> findByEntityClassId(String entityClass, String id) {

    try {
        Class<?> cl = Class.forName(entityClass);
        EntityType<?> entityType = em.getEntityManagerFactory().getMetamodel().entity(cl);
        if (entityType != null && entityType.getBindableJavaType().getAnnotation(PortalTable.class) != null) {
            if (entityType.getBindableJavaType().getName().equals(entityClass)) {
                Class<?> bindableJavaType = entityType.getBindableJavaType();
                //select

                CriteriaBuilder cb = em.getCriteriaBuilder();
                CriteriaQuery<?> cq = cb.createQuery(bindableJavaType);
                Root<?> root = cq.from(User.class);

                cq.where(cb.equal(root.get("id"), Long.parseLong(id)));

                TypedQuery<?> query = em.createQuery(cq);
                ParameterExpression<Long> parameter = cb.parameter(Long.class, "id");
                //query.setParameter(parameter, Long.parseLong(id));
                //query.unwrap(org.hibernate.Query.class).getQueryString();

                Object result = query.getSingleResult();

                List<String> columns = getTableOrViewMetaData(entityClass);

                HashMap<String, String> res = new HashMap<>(columns.size());
                Class<? extends Object> clazz = result.getClass();
                for (String fieldName : columns) {
                    try {
                        Field field = clazz.getDeclaredField(fieldName);
                        field.setAccessible(true);
                        Object fieldValue = field.get(result);
                        res.put(fieldName, fieldValue.toString());
                    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                            | IllegalAccessException ex) {
                        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                System.out.println(res);
                Map<EntityType<?>, Map<String, String>> hm = new HashMap<>();
                hm.put(entityType, res);
                return hm;

            }
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(TableServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:eu.uqasar.service.ProcessService.java

private List<Predicate> getFilterPredicates(final ProcessesFilterStructure filter, CriteriaBuilder cb,
        Root<Process> from) {
    List<Predicate> predicates = new ArrayList<>();
    if (filter == null) {
        return predicates;
    }//from   w  w  w . jav  a  2  s.  com

    if (filter.getStartDate() != null) {
        predicates.add(cb.equal(from.get(Process_.startDate), filter.getStartDate()));
    }
    if (filter.getEndDate() != null) {
        predicates.add(cb.equal(from.get(Process_.endDate), filter.getEndDate()));
    }

    if (!StringUtils.isEmpty(filter.getName())) {
        Predicate firstName = cb.like(cb.lower(from.get(Process_.name)),
                LIKE_WILDCARD + filter.getName().toLowerCase() + LIKE_WILDCARD);
        predicates.add((firstName));
    }
    return predicates;
}

From source file:com.sapito.db.dao.AbstractDao.java

public List<T> findBySpecificField(String field, Object fieldContent, String predicates,
        LinkedHashMap<String, String> ordering, LinkedList<String> grouping) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery cq = cb.createQuery();
    Root<T> root = cq.from(entityClass);
    Predicate predicate = null;// w  ww  . ja  v a 2  s .  c om

    if (predicates.equals("equal")) {
        predicate = cb.equal(root.get(field), fieldContent);
    } else if (predicates.equals("likelower")) {
        predicate = cb.like(cb.lower(root.<String>get(field)), fieldContent.toString());
    } else if (predicates.equals("like")) {
        predicate = cb.like(root.<String>get(field), "%" + fieldContent.toString() + "%");
    }

    cq.select(root);
    cq.where(predicate);

    if (ordering != null) {
        Set<String> set = ordering.keySet();
        List<Order> orders = new ArrayList<>();
        for (String orderingField : set) {
            Order order;
            if (ordering.get(orderingField).equals("ASC")) {
                order = cb.asc(root.get(orderingField));
            } else {
                order = cb.desc(root.get(orderingField));
            }
            orders.add(order);
        }
        cq.orderBy(orders);
    }

    if (grouping != null) {
        Iterator iterator = grouping.iterator();
        List<Expression> groups = new LinkedList<>();
        while (iterator.hasNext()) {
            groups.add(root.get(iterator.next().toString()));
        }
        cq.groupBy(groups);
    }

    Query query = entityManager.createQuery(cq);
    query.setMaxResults(MAX_RECORDS_RETURNED);

    return query.getResultList();
}