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:org.osiam.resource_server.storage.dao.ResourceDao.java

public <T extends ResourceEntity, V> boolean isUniqueAttributeAlreadyTaken(String attributeValue, String id,
        SingularAttribute<? super T, V> attribute, Class<T> clazz) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Long> cq = cb.createQuery(Long.class);
    Root<T> resource = cq.from(clazz);

    cq.select(cb.countDistinct(resource));

    Predicate predicate = cb.equal(resource.get(attribute), attributeValue);
    if (id != null) {
        Predicate ignoreId = cb.notEqual(resource.get(ResourceEntity_.id), id);
        predicate = cb.and(predicate, ignoreId);
    }/*from w  w  w.j  a  v a2 s  .  com*/
    cq.where(predicate);

    TypedQuery<Long> countQuery = em.createQuery(cq);

    return countQuery.getSingleResult() > 0;
}

From source file:com.alliander.osgp.adapter.ws.infra.specifications.JpaDeviceSpecifications.java

@Override
public Specification<Device> hasDeviceIdentification(final String deviceIdentification,
        final boolean exactMatch) throws ArgumentNullOrEmptyException {
    if (StringUtils.isEmpty(deviceIdentification)) {
        throw new ArgumentNullOrEmptyException("deviceIdentification");
    }/*w w w  .jav a2 s. c  o  m*/

    return new Specification<Device>() {
        @Override
        public Predicate toPredicate(final Root<Device> deviceRoot, final CriteriaQuery<?> query,
                final CriteriaBuilder cb) {
            if (exactMatch) {
                return cb.equal(cb.upper(deviceRoot.<String>get("deviceIdentification")), deviceIdentification);
            } else {
                return cb.like(cb.upper(deviceRoot.<String>get("deviceIdentification")),
                        deviceIdentification.toUpperCase());
            }
        }
    };
}

From source file:br.com.sementesdoamanha.repository.Servidores.java

public List<Servidor> filtrados(ServidorFilter filtro) {
    //select, from, where, like... --> select(), from(), where()
    //JPQL: from Servidor

    //JPQL: select s from Servidor s where c.nome like = 'Joo%' and c.cpf = like '046.244.901-77'
    CriteriaBuilder builder = manager.getCriteriaBuilder();
    CriteriaQuery<Servidor> criteriaQuery = builder.createQuery(Servidor.class);
    Root<Servidor> s = criteriaQuery.from(Servidor.class);
    criteriaQuery.select(s);/*from   www .  j av a  2 s.  c  o  m*/

    List<Predicate> predicates = new ArrayList<>();

    if (StringUtils.isNotBlank(filtro.getCpf())) {
        predicates.add(builder.equal(s.<String>get("cpf"), filtro.getCpf()));
    }
    if (StringUtils.isNotBlank(filtro.getNome())) {
        predicates
                .add(builder.like(builder.upper(s.<String>get("nome")), filtro.getNome().toUpperCase() + "%"));

    }

    criteriaQuery.where(predicates.toArray(new Predicate[0]));
    TypedQuery<Servidor> query = manager.createQuery(criteriaQuery);
    return query.getResultList();

}

From source file:net.dontdrinkandroot.persistence.dao.ExampleGeneratedIdEntityDaoImpl.java

@Override
@Transactional(readOnly = true)/*from w  w  w .j  ava2s. c o  m*/
public ExampleGeneratedIdEntity findWithOthersFetchJoin(final Long id) {
    final CriteriaBuilder builder = this.getCriteriaBuilder();
    final CriteriaQuery<ExampleGeneratedIdEntity> criteriaQuery = builder
            .createQuery(ExampleGeneratedIdEntity.class);
    final Root<ExampleGeneratedIdEntity> root = criteriaQuery.from(this.entityClass);
    root.fetch(ExampleGeneratedIdEntity_.otherEntities);

    criteriaQuery.where(builder.equal(root.get(ExampleGeneratedIdEntity_.id), id));

    return this.findSingle(criteriaQuery);
}

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

public Page<CouponCode> findPage(Member member, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<CouponCode> criteriaQuery = criteriaBuilder.createQuery(CouponCode.class);
    Root<CouponCode> root = criteriaQuery.from(CouponCode.class);
    criteriaQuery.select(root);//from w  w  w . j  ava2  s.  c  om
    if (member != null) {
        criteriaQuery.where(criteriaBuilder.equal(root.get("member"), member));
    }
    return super.findPage(criteriaQuery, pageable);
}

From source file:com.vladmihalcea.HibernateFetchStrategyTest.java

@Test
public void test() {

    final Long productId = transactionTemplate.execute(new TransactionCallback<Long>() {
        @Override/*from  ww w  .j  a v  a 2s. c om*/
        public Long doInTransaction(TransactionStatus transactionStatus) {

            Company company = new Company();
            company.setName("TV Company");
            entityManager.persist(company);

            Product product = new Product("tvCode");
            product.setName("TV");
            product.setCompany(company);

            Image frontImage = new Image();
            frontImage.setName("front image");
            frontImage.setIndex(0);

            Image sideImage = new Image();
            sideImage.setName("side image");
            sideImage.setIndex(1);

            product.addImage(frontImage);
            product.addImage(sideImage);

            WarehouseProductInfo warehouseProductInfo = new WarehouseProductInfo();
            warehouseProductInfo.setQuantity(101);
            product.addWarehouse(warehouseProductInfo);

            Importer importer = new Importer();
            importer.setName("Importer");
            entityManager.persist(importer);
            product.setImporter(importer);

            entityManager.persist(product);
            return product.getId();
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            LOG.info("Fetch using find");
            Product product = entityManager.find(Product.class, productId);
            assertNotNull(product);
            return null;
        }
    });

    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            LOG.info("Fetch using JPQL");
            Product product = entityManager
                    .createQuery("select p " + "from Product p " + "where p.id = :productId", Product.class)
                    .setParameter("productId", productId).getSingleResult();
            assertNotNull(product);
            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {

            LOG.info("Fetch using Criteria");

            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery<Product> cq = cb.createQuery(Product.class);
            Root<Product> productRoot = cq.from(Product.class);
            cq.where(cb.equal(productRoot.get("id"), productId));
            Product product = entityManager.createQuery(cq).getSingleResult();
            assertNotNull(product);
            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {
            LOG.info("Fetch using join fetch JPQL");

            Product product = product = entityManager.createQuery("select p " + "from Product p "
                    + "inner join fetch p.warehouseProductInfo " + "inner join fetch p.importer", Product.class)
                    .getSingleResult();
            assertNotNull(product);

            return null;
        }
    });
    transactionTemplate.execute(new TransactionCallback<Void>() {
        @Override
        public Void doInTransaction(TransactionStatus transactionStatus) {

            Image image = entityManager
                    .createQuery("select i " + "from Image i " + "inner join fetch i.product p "
                            + "where p.id = :productId", Image.class)
                    .setParameter("productId", productId).getResultList().get(0);
            assertNotNull(image);

            return null;
        }
    });
}

From source file:org.openmeetings.app.data.basic.dao.LdapConfigDaoImpl.java

public List<LdapConfig> getLdapConfigs(int start, int max, String orderby, boolean asc) {
    try {// w w  w  .  jav  a  2  s.  c om
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<LdapConfig> cq = cb.createQuery(LdapConfig.class);
        Root<LdapConfig> c = cq.from(LdapConfig.class);
        Predicate condition = cb.equal(c.get("deleted"), "false");
        cq.where(condition);
        cq.distinct(asc);
        if (asc) {
            cq.orderBy(cb.asc(c.get(orderby)));
        } else {
            cq.orderBy(cb.desc(c.get(orderby)));
        }
        TypedQuery<LdapConfig> q = em.createQuery(cq);
        q.setFirstResult(start);
        q.setMaxResults(max);
        List<LdapConfig> ll = q.getResultList();
        return ll;
    } catch (Exception ex2) {
        log.error("[getLdapConfigs]", ex2);
    }
    return null;
}

From source file:cz.muni.expense.data.UserRepository.java

public User findByUsernameAndPassword(String username, String password) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> criteria = cb.createQuery(User.class);
    Root<User> user = criteria.from(User.class);
    // Swap criteria statements if you would like to try out type-safe criteria queries, a new
    // feature in JPA 2.0
    //criteria.select(member).where(cb.equal(member.get(Member_.name), email));
    criteria.select(user).where(cb.equal(user.get(User_.username), username));
    try {/* w  ww  .  j av a2 s .  c om*/
        User userToReturn = em.createQuery(criteria).getSingleResult();
        String hash = org.apache.commons.codec.digest.DigestUtils.sha256Hex(password);
        return userToReturn.getPasswdHash().equals(hash) ? userToReturn : null;
    } catch (NoResultException ex) {
        return null;
    }
}

From source file:com.june.app.board.repository.jpa.BoardRepositoryImpl.java

@Override
public Collection<Board> boardListWithPaging(Board vo) {
    int bbsId = vo.getBbsId();
    int pageSize = vo.getPageSize();
    int pageNumber = (int) vo.getPageIndex();

    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<Board> criteriaQuery = criteriaBuilder.createQuery(Board.class);

    Root<Board> from = criteriaQuery.from(Board.class);
    CriteriaQuery<Board> select = criteriaQuery.select(from);
    if (bbsId > 0) {
        criteriaQuery.where(criteriaBuilder.equal(from.get("bbsId"), bbsId));
    }//w w w . j a v a2 s .  c  om
    /**list desc for date*/
    criteriaQuery.orderBy(criteriaBuilder.desc(from.get("frstRegistPnttm")));
    TypedQuery<Board> typedQuery = em.createQuery(select);

    typedQuery.setFirstResult((pageNumber - 1) * pageSize);
    typedQuery.setMaxResults(pageSize);

    Collection<Board> fooList = typedQuery.getResultList();

    return fooList;

}

From source file:com.june.app.board.repository.jpa.BoardRepositoryImpl.java

@Override
public long boardListCnt(Board vo) {

    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();

    int bbsId = vo.getBbsId();
    CriteriaQuery<Long> countQuery = criteriaBuilder.createQuery(Long.class);
    Root<Board> from = countQuery.from(Board.class);
    countQuery.select(criteriaBuilder.count(from));
    if (bbsId > 0) {
        countQuery.where(criteriaBuilder.equal(from.get("bbsId"), bbsId));
    }//from  www  . j a  v a 2 s .co  m
    Long count = em.createQuery(countQuery).getSingleResult();

    return count;

}