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:se.kth.csc.persist.JPAStore.java

@Override
public Iterable<Account> findAccounts(boolean onlyAdmin, String query) {
    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<Account> q = cb.createQuery(Account.class);
    Root<Account> account = q.from(Account.class);

    Expression<Boolean> expression = null;

    if (onlyAdmin) {
        // This looks like it could be replaced with account.get(Account_.admin), but it can't because of syntax
        expression = cb.equal(account.get(Account_.admin), true);
    }//w  ww . ja v a  2s  .c  om

    if (query != null) {
        Expression<Boolean> queryExpression = cb.like(cb.lower(account.get(Account_.name)),
                "%" + query.toLowerCase() + "%");

        if (expression == null) {
            expression = queryExpression;
        } else {
            expression = cb.and(expression, queryExpression);
        }
    }

    if (expression != null) {
        q.where(expression);
    }

    return entityManager.createQuery(q.select(account)).getResultList();
}

From source file:edu.sabanciuniv.sentilab.sare.models.base.documentStore.PersistentDocumentStore.java

/**
 * Gets identifiers of documents in this store.
 * @param em the {@link EntityManager} to get the documents from.
 * @return an {@link Iterable} of document identifiers.
 *//* ww  w .j a  v a  2 s  . c om*/
public Iterable<byte[]> getDocumentIds(EntityManager em) {
    Validate.notNull(em, CannedMessages.NULL_ARGUMENT, "em");

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<byte[]> cq = cb.createQuery(byte[].class);
    Root<PersistentDocument> doc = cq.from(PersistentDocument.class);
    cq.multiselect(doc.get("id"))
            .where(cb.equal(doc.get("store"), cb.parameter(PersistentDocumentStore.class, "store")));
    TypedQuery<byte[]> tq = em.createQuery(cq);
    tq.setParameter("store", this);
    return tq.getResultList();
}

From source file:com.wms.studio.service.LoginIpServiceImpl.java

@Override
@org.springframework.transaction.annotation.Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
public PageDto<LoginIpInfoDto> findBy(final String userId, final Date start, final Date end,
        PageSize pageSize) {//  w  w  w. jav  a  2s .co m

    if (pageSize == null) {
        pageSize = new PageSize();
    }

    return loginIpConvert.covertToDto(loginIpRepository.findAll(new Specification<LoginIp>() {

        @Override
        public Predicate toPredicate(Root<LoginIp> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
            List<Predicate> pres = new ArrayList<>(3);

            if (start != null) {
                pres.add(cb.greaterThanOrEqualTo(root.get("loginTime").as(Date.class), start));
            }

            if (end != null) {
                pres.add(cb.lessThanOrEqualTo(root.get("loginTime").as(Date.class), end));
            }

            if (!StringUtils.isBlank(userId)) {
                pres.add(cb.equal(root.get("user").as(User.class), new User(userId)));
            }

            Predicate[] p = new Predicate[pres.size()];
            return cb.and(pres.toArray(p));
        }
    }, new PageRequest(pageSize.getPage() - 1, pageSize.getLimit())));
}

From source file:net.groupbuy.dao.impl.MessageDaoImpl.java

public Page<Message> findPage(Member member, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Message> criteriaQuery = criteriaBuilder.createQuery(Message.class);
    Root<Message> root = criteriaQuery.from(Message.class);
    criteriaQuery.select(root);//from  w  w  w  .j  a  v  a2 s .  c  om
    Predicate restrictions = criteriaBuilder.conjunction();
    restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNull(root.get("forMessage")),
            criteriaBuilder.equal(root.get("isDraft"), false));
    if (member != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(
                        criteriaBuilder.and(criteriaBuilder.equal(root.get("sender"), member),
                                criteriaBuilder.equal(root.get("senderDelete"), false)),
                        criteriaBuilder.and(criteriaBuilder.equal(root.get("receiver"), member),
                                criteriaBuilder.equal(root.get("receiverDelete"), false))));
    } else {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(
                        criteriaBuilder.and(criteriaBuilder.isNull(root.get("sender")),
                                criteriaBuilder.equal(root.get("senderDelete"), false)),
                        criteriaBuilder.and(criteriaBuilder.isNull(root.get("receiver")),
                                criteriaBuilder.equal(root.get("receiverDelete"), false))));
    }
    criteriaQuery.where(restrictions);
    return super.findPage(criteriaQuery, pageable);

}

From source file:com.aimdek.ccm.dao.impl.CreditCardRepositoryImpl.java

/**
 * {@inheritDoc}/*from   w  ww  .  j a  v a2 s. c  o  m*/
 */
public long getCustomerCreditCardsCount(long userId) {

    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Long> query = builder.createQuery(Long.class);
    Root<CreditCard> root = query.from(CreditCard.class);
    query.select(builder.count(root));

    if (CommonUtil.isNotNull(userId)) {
        User user = userRepository.findById(userId);
        if (CommonUtil.isNotNull(user) && user.getRole().equals(ROLE_CUSTOMER)) {
            query.where(builder.equal(root.<Long>get(FIELDCONSTANT_CARDHOLDERID), user.getId()));
        }
    }
    return entityManager.createQuery(query).getSingleResult();
}

From source file:eu.uqasar.service.user.UserService.java

private List<Predicate> getFilterPredicates(final UserFilterStructure filter, CriteriaBuilder cb,
        Root<User> from) {/*  ww w  .ja v  a  2s  .c  o  m*/
    List<Predicate> predicates = new ArrayList<>();
    if (filter == null) {
        return predicates;
    }

    if (filter.getRole() != null) {
        predicates.add(cb.equal(from.get(User_.userRole), filter.getRole()));
    }
    if (filter.getSource() != null) {
        predicates.add(cb.equal(from.get(User_.source), filter.getSource()));
    }
    if (filter.getStatus() != null) {
        predicates.add(cb.equal(from.get(User_.registrationStatus), filter.getStatus()));
    }
    if (!StringUtils.isEmpty(filter.getName())) {
        Predicate firstName = cb.like(cb.lower(from.get(User_.lastName)),
                LIKE_WILDCARD + filter.getName().toLowerCase() + LIKE_WILDCARD);
        Predicate lastName = cb.like(from.get(User_.firstName),
                LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);
        Predicate userName = cb.like(from.get(User_.userName),
                LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);
        Expression<String> fullName = cb.concat(cb.concat(from.get(User_.firstName), " "),
                from.get(User_.lastName));
        Expression<String> un = cb.concat(" (", cb.concat(from.get(User_.userName), ")"));
        Predicate fn = cb.like(fullName, LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);
        Expression<String> fnu = cb.concat(fullName, un);
        Predicate ff1 = cb.like(fnu, LIKE_WILDCARD + filter.getName() + LIKE_WILDCARD);

        predicates.add(cb.or(firstName, lastName, userName, fn, ff1));

    }
    return predicates;
}

From source file:org.jboss.quickstarts.wfk.contact.ContactRepository.java

/**
 * Find just one Contact by the last name that is passed in. If there is more then one, only the first will be returned.
 * /*from   www  .  ja  va 2 s . co  m*/
 * @param lastName
 * @return Contact
 */
Contact findByLastName(String lastName) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Contact> criteria = cb.createQuery(Contact.class);
    Root<Contact> contact = criteria.from(Contact.class);
    // Swap criteria statements if you would like to try out type-safe criteria queries, a new feature in JPA 2.0.
    // criteria.select(contact).where(cb.equal(contact.get(Contact_.lastName), lastName));
    criteria.select(contact).where(cb.equal(contact.get("lastName"), lastName));
    return em.createQuery(criteria).getSingleResult();
}

From source file:com.home.ln_spring.ch10.service.jpa.ContactServiceImplOld.java

@Override
@Transactional(readOnly = true)//w ww . j  a v a  2s.c  o  m
public List<Contact> findByCriteriaQuery(String firstName, String lastName) {
    log.info("Finding contact for firstName: " + firstName + " and lastName: " + lastName);

    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Contact> criteriaQuery = cb.createQuery(Contact.class);
    Root<Contact> contactRoot = criteriaQuery.from(Contact.class);
    contactRoot.fetch(Contact_.contactTelDetails, JoinType.LEFT);
    contactRoot.fetch(Contact_.hobbies, JoinType.LEFT);

    criteriaQuery.select(contactRoot).distinct(true);

    Predicate criteria = cb.conjunction();
    if (firstName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.firstName), firstName);
        criteria = cb.and(criteria, p);
    }

    if (lastName != null) {
        Predicate p = cb.equal(contactRoot.get(Contact_.lastName), lastName);
        criteria = cb.and(criteria, p);
    }

    criteriaQuery.where(criteria);
    List<Contact> result = em.createQuery(criteriaQuery).getResultList();
    return result;
}

From source file:org.jboss.quickstarts.wfk.contact.ContactRepository.java

/**
 * Find just one Contact by the first name that is passed in. If there is more then one, only the first will be returned.
 * /*ww w  .j  a  v  a2 s.  c om*/
 * @param firstName
 * @return Contact
 */
Contact findByFirstName(String firstName) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Contact> criteria = cb.createQuery(Contact.class);
    Root<Contact> contact = criteria.from(Contact.class);
    // Swap criteria statements if you would like to try out type-safe criteria queries, a new feature in JPA 2.0.
    // criteria.select(contact).where(cb.equal(contact.get(Contact_.firstName), firstName));
    criteria.select(contact).where(cb.equal(contact.get("firstName"), firstName));
    return em.createQuery(criteria).getSingleResult();
}

From source file:bq.jpa.demo.query.criteria.service.CriteriaService.java

/**
 * NOTE : Hibernate cannot support case in criteria way
 * /*  ww w. jav  a 2  s .c  om*/
 * case 1:
 * SELECT p.name, 
 *          CASE WHEN TYPE(p)=bq.jpa.demo.query.domain.DesignProject  THEN 'dev' 
 *              WHEN TYPE(p)=bq.jpa.demo.query.domain.QualityProject THEN 'QA' 
 *              ELSE 'unknown' 
 *          END 
 * FROM jpa_query_project p
 * 
 * case 2:
 * SELECT p.name, 
 *          CASE TYPE(p)
 *              WHEN bq.jpa.demo.query.domain.DesignProject  THEN 'dev' 
 *              WHEN bq.jpa.demo.query.domain.QualityProject THEN 'QA' 
 *              ELSE 'unknown' 
 *          END 
 * FROM jpa_query_project p
 */
@Transactional
public void doWhere4() {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Object[]> c = cb.createQuery(Object[].class);
    Root<Project> p = c.from(Project.class);

    // method 1
    c.multiselect(p.get("name"), cb.selectCase().when(cb.equal(p.type(), DesignProject.class), "dev")
            .when(cb.equal(p.type(), QualityProject.class), "QA").otherwise("unknown"));

    //      showResult(c);

    // method 2:
    CriteriaQuery<Object[]> c2 = cb.createQuery(Object[].class);
    Root<Project> p2 = c2.from(Project.class);
    c2.multiselect(p2.get("name"), cb.selectCase(p2.type()).when(DesignProject.class, "dev")
            .when(QualityProject.class, "QA").otherwise("unknown"));
    //      showResult(c2);
}