Java Code Examples for javax.persistence.criteria.CriteriaBuilder.createQuery()

The following are Jave code examples for showing how to use createQuery() of the javax.persistence.criteria.CriteriaBuilder class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License Vote up 17 votes
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/{regionName}/{orderLineId}")
public List<LiveSalesList> findRecentRegionFrom(@PathParam("regionName") String regionName, @PathParam("orderLineId") Integer orderLineId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
        cb.equal(liveSalesList.get(LiveSalesList_.region), regionName),
        cb.gt(liveSalesList.get(LiveSalesList_.orderLineId), orderLineId)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 2
Project: photoiff   File: PerfilService.java   Source Code and License Vote up 8 votes
public Pessoa validarUsuario(String log, String pass){
	final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
	
	final CriteriaQuery<Pessoa> cquery = cb.createQuery(Pessoa.class);
	final Root<Pessoa> root = cquery.from(Pessoa.class);
	final List<Predicate> condicoes = new ArrayList<Predicate>();

	condicoes.add(cb.equal(root.get("usuario").get("login"), log));
	condicoes.add(cb.equal(root.get("usuario").get("senha"), pass));
	
	cquery.select(root).where(condicoes.toArray(new Predicate[]{}));
	Pessoa pessoa = new Pessoa();
	try{
		pessoa = getEntityManager().createQuery(cquery).getSingleResult();
	} catch (Exception e) {
		throw new QueryTimeoutException("Usuário ou senha invalido!");
	}	
   	
   	return pessoa;
}
 
Example 3
Project: otus_java_2017_10   File: ConnectionHelper.java   Source Code and License Vote up 8 votes
private static void _criteria(DbService dbService) {
    final EntityManager em = dbService.getEntityManager();

    // INSERT new record
    em.getTransaction().begin();
    em.persist(new Account("A"));
    em.persist(new Account("B"));
    em.persist(new Account("C"));
    em.getTransaction().commit();



    CriteriaBuilder builder = em.getCriteriaBuilder();
    CriteriaQuery<Account> query = builder.createQuery(Account.class);
    Root<Account> acc = query.from(Account.class);

    Predicate cond = builder.gt(acc.get("id"), 1);
    query.where(cond);
    TypedQuery<Account> q = em.createQuery(query);
    List<Account> resultList = q.getResultList();
    System.out.println(resultList);


}
 
Example 4
Project: osc-core   File: VirtualizationConnectorEntityMgr.java   Source Code and License Vote up 6 votes
public static boolean isControllerTypeUsed(String controllerType, EntityManager em) {

        Long count = 0L;
        try {
            CriteriaBuilder cb = em.getCriteriaBuilder();

            CriteriaQuery<Long> query = cb.createQuery(Long.class);

            Root<VirtualizationConnector> root = query.from(VirtualizationConnector.class);

            query = query.select(cb.count(root))
                    .where(cb.equal(root.get("controllerType"), controllerType));

            count = em.createQuery(query).getSingleResult();
        } catch (Exception e) {
            // Ignore this exception
        }

        return count > 0;
    }
 
Example 5
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License Vote up 6 votes
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/producttype/{regionName}/{productTypeId}")
public List<LiveSalesList> findRecentRegionProductType(@PathParam("regionName") String regionName, @PathParam("productTypeId") Integer productTypeId) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.and(
            cb.equal(liveSalesList.get(LiveSalesList_.productTypeId), productTypeId), 
            cb.equal(liveSalesList.get(LiveSalesList_.region), regionName)
    ));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 6
Project: osc-core   File: SubnetEntityManager.java   Source Code and License Vote up 6 votes
public static Subnet findByOpenstackId(EntityManager em, String id) {

        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<Subnet> query = cb.createQuery(Subnet.class);

        Root<Subnet> root = query.from(Subnet.class);

        query = query.select(root)
            .where(cb.equal(root.get("openstackId"), id));

        try {
            return em.createQuery(query).getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
    }
 
Example 7
Project: osc-core   File: VMPortEntityManager.java   Source Code and License Vote up 6 votes
public static VMPort findByOpenstackId(EntityManager em, String id) {

        CriteriaBuilder cb = em.getCriteriaBuilder();

        CriteriaQuery<VMPort> query = cb.createQuery(VMPort.class);

        Root<VMPort> root = query.from(VMPort.class);

        query = query.select(root)
            .where(cb.equal(root.get("openstackId"), id));

        try {
            return em.createQuery(query).getSingleResult();
        } catch (NoResultException nre) {
            return null;
        }
    }
 
Example 8
Project: jwala   File: AbstractCrudServiceImpl.java   Source Code and License Vote up 5 votes
public List<T> findAll() {
    final CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    final CriteriaQuery<T> criteria = builder.createQuery(entityClass);
    final Root<T> root = criteria.from(entityClass);
    criteria.select(root);

    final TypedQuery<T> query = entityManager.createQuery(criteria);

    return query.getResultList();
}
 
Example 9
Project: linq   File: JpaUtil.java   Source Code and License Vote up 5 votes
/**
 * 分页查询
 * @param domainClass 领域类(实体类)
 * @param pageable 分页信息
 * @param <T> 领域类(实体类)范型
 * @return 分页结果信息
 */
public static <T> Page<T> findAll(Class<T> domainClass, Pageable pageable) {
	EntityManager em = getEntityManager(domainClass);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<T> cq = cb.createQuery(domainClass);
	cq.from(domainClass);
	return findAll(cq, pageable);
}
 
Example 10
Project: osc-core   File: SecurityGroupEntityMgr.java   Source Code and License Vote up 5 votes
public static List<SecurityGroup> listByProjectId(EntityManager em, String projectId) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class);

    Root<SecurityGroup> root = query.from(SecurityGroup.class);
    query = query.select(root)
            .distinct(true)
            .where(cb.equal(root.get("projectId"), projectId));

    return em.createQuery(query).getResultList();
}
 
Example 11
Project: marathonv5   File: LiveSalesListFacadeREST.java   Source Code and License Vote up 5 votes
@GET
@Produces({"application/xml", "application/json"})
@Path("/recent/region/{regionName}")
public List<LiveSalesList> findRecentRegion(@PathParam("regionName") String regionName) {
    CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
    javax.persistence.criteria.CriteriaQuery cq = cb.createQuery();
    Root<LiveSalesList> liveSalesList = cq.from(LiveSalesList.class);
    cq.select(liveSalesList);
    cq.where(cb.equal(liveSalesList.get(LiveSalesList_.region), regionName));
    Query q = getEntityManager().createQuery(cq);
    q.setMaxResults(500);
    return q.getResultList();
}
 
Example 12
Project: java-jwt-auth   File: UserDao.java   Source Code and License Vote up 5 votes
public User findUserById(Long id) {
    try (Session session = HibernateUtil.getSessionFactory().openSession()) {
        CriteriaBuilder builder = session.getCriteriaBuilder();
        CriteriaQuery<User> criteria = builder.createQuery(User.class);
        Root<User> root = criteria.from(User.class);
        criteria.select(root).where(builder.equal(root.get("id"), id));
        Query<User> q = session.createQuery(criteria);
        return q.getSingleResult();
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
    }
    return null;
}
 
Example 13
Project: photoiff   File: PerfilService.java   Source Code and License Vote up 5 votes
public List<Pessoa> filtrarPorNome(String filtro){
	final CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
	
	final CriteriaQuery<Pessoa> cquery = cb.createQuery(Pessoa.class);
	final Root<Pessoa> root = cquery.from(Pessoa.class);
	final List<Predicate> condicoes = new ArrayList<Predicate>();

	Expression<String> path = root.get("nome");
	condicoes.add(cb.like(path, "%"+filtro+"%"));
	
	cquery.select(root).where(condicoes.toArray(new Predicate[]{}));
	List<Pessoa> pessoas = getEntityManager().createQuery(cquery).getResultList();
		    	
   	return pessoas;
}
 
Example 14
Project: osc-core   File: JobEntityManager.java   Source Code and License Vote up 5 votes
public List<JobRecord> getUncompletedJobs(EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<JobRecord> query = cb.createQuery(JobRecord.class);

    Root<JobRecord> from = query.from(JobRecord.class);
    query = query.select(from)
            .where(cb.notEqual(from.get("state"), COMPLETED));
    return em.createQuery(query).getResultList();
}
 
Example 15
Project: osc-core   File: SecurityGroupEntityMgr.java   Source Code and License Vote up 5 votes
/**
 * @param em
 *            Hibernate EntityManager
 * @param sg
 *            Security Group
 * @return
 *         true if any SGM was deleted
 *         false if no SGM was deleted
 */
public static boolean hasSGMRemoved(EntityManager em, SecurityGroup sg) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<SecurityGroup> query = cb.createQuery(SecurityGroup.class);

    Root<SecurityGroup> root = query.from(SecurityGroup.class);
    Join<SecurityGroup, Object> join = root.join("securityGroupMembers");
    query = query.select(root)
            .distinct(true)
            .where(cb.equal(join.get("markedForDeletion"), true));

    return !em.createQuery(query).setMaxResults(1).getResultList().isEmpty();
}
 
Example 16
Project: OperatieBRP   File: CustomSimpleMaxedJpaRepository.java   Source Code and License Vote up 4 votes
@Override
protected TypedQuery<Long> getCountQuery(final Specification<T> spec) {
    final CriteriaBuilder builder = em.getCriteriaBuilder();
    final CriteriaQuery<T> criteria = builder.createQuery(getDomainClass());
    final Root<T> root = applySpecificationToQueryCriteria(spec, criteria);
    criteria.select(root);
    final TypedQuery<T> query = em.createQuery(criteria);

    
    final AbstractQueryImpl hibernateQuery = query.unwrap(AbstractQueryImpl.class);
    @SuppressWarnings("unchecked")
    final Map<String, TypedValue> pNamedParameters = (Map<String, TypedValue>) getField(hibernateQuery, AbstractQueryImpl.class, "namedParameters");

    final String hql = hibernateQuery.getQueryString();

    final ASTQueryTranslatorFactory queryTranslatorFactory = new ASTQueryTranslatorFactory();
    final SessionImplementor hibernateSession = em.unwrap(SessionImplementor.class);
    final QueryTranslator queryTranslator =
            queryTranslatorFactory.createQueryTranslator("", hql, Collections.emptyMap(), hibernateSession.getFactory(), null);
    queryTranslator.compile(Collections.emptyMap(), false);
    final String sql = queryTranslator.getSQLString();
    final ParameterTranslations paramTranslations = queryTranslator.getParameterTranslations();

    final String countSql = String.format("select count(*) from (%s limit %d) as sqry", sql, maximumRecords + 1);

    final Query nativeQuery = em.createNativeQuery(countSql);

    
    final AbstractQueryImpl resultQuery = nativeQuery.unwrap(AbstractQueryImpl.class);

    if (pNamedParameters != null) {
        for (final Entry<String, TypedValue> entry : pNamedParameters.entrySet()) {
            for (final int index : paramTranslations.getNamedParameterSqlLocations(entry.getKey())) {

                resultQuery.setParameter(index, entry.getValue().getValue(), entry.getValue().getType());
            }
        }
    }

    return new CustomCountQueryWrapper(nativeQuery);
}
 
Example 17
Project: xsharing-services-router   File: StationRepositoryImpl.java   Source Code and License Vote up 4 votes
@Override
public void saveSharingStationList(List<? extends SharingStation> stations) {

    // -------------------------------------------------------------------------
    // 1. Get all stations in order to decide whether to insert or update
    // -------------------------------------------------------------------------

    CriteriaBuilder cb = entityManager.getCriteriaBuilder();
    CriteriaQuery<SharingStation> s = cb.createQuery(SharingStation.class);

    Root<SharingStation> station = s.from(SharingStation.class);
    CriteriaQuery<SharingStation> all = s.select(station);

    TypedQuery<SharingStation> allQuery = entityManager.createQuery(all);
    List<SharingStation> dbList = allQuery.getResultList();

    // -------------------------------------------------------------------------
    // 2. Decide to insert or update
    // -------------------------------------------------------------------------

    Map<Boolean, List<SharingStation>> partition =
            stations.stream()
                    .collect(Collectors.partitioningBy(newEntry -> {
                        for (SharingStation dbEntry : dbList) {
                            if (newEntry.isSame(dbEntry)) {
                                // is already in db
                                return true;
                            }
                        }
                        // not found in db
                        return false;
                    }));

    // TODO: what about stations that should be deleted?
    //
    List<SharingStation> toInsert = partition.get(Boolean.FALSE);
    List<SharingStation> toUpdate = partition.get(Boolean.TRUE);

    log.info("# of stations to insert: {}, to update: {}", toInsert.size(), toUpdate.size());

    // -------------------------------------------------------------------------
    // 3. Insert new stations
    // -------------------------------------------------------------------------

    try {
        saveList(toInsert);
    } catch (DatabaseException | EJBTransactionRolledbackException | PersistenceException e) {
        log.error("Error on insert! {}", e.getMessage());
    }

    // -------------------------------------------------------------------------
    // 4. Update existing stations
    // -------------------------------------------------------------------------

    final String query = "UPDATE SharingStation ss SET " +
                         "ss.globalId = :globalId, " +
                         "ss.geoPos = :geoPos, " +
                         "ss.capacity = :capacity, " +
                         "ss.availableCapacity = :availableCapacity, " +
                         "ss.availableVehicles = :availableVehicles, " +
                         "ss.name = :name " +
                         "WHERE ss.providerId = :providerId " +
                         "AND ss.placeId = :placeId";

    for (SharingStation sd : toUpdate) {
        entityManager.createQuery(query)
                     .setParameter("globalId", sd.getGlobalId())
                     .setParameter("geoPos", sd.getGeoPos())
                     .setParameter("capacity", sd.getCapacity())
                     .setParameter("availableCapacity", sd.getAvailableCapacity())
                     .setParameter("availableVehicles", sd.getAvailableVehicles())
                     .setParameter("name", sd.getName())
                     .setParameter("providerId", sd.getProviderId())
                     .setParameter("placeId", sd.getPlaceId())
                     .executeUpdate();
    }
}
 
Example 18
Project: sdn-controller-nsc-plugin   File: RedirectionApiUtils.java   Source Code and License Vote up 3 votes
public List<InspectionHookEntity> txInspectionHookEntitiesByInspected(String inspectedId) {

        CriteriaBuilder cb = this.em.getCriteriaBuilder();
        CriteriaQuery<InspectionHookEntity> criteria = cb.createQuery(InspectionHookEntity.class);
        Root<InspectionHookEntity> root = criteria.from(InspectionHookEntity.class);

        criteria.select(root).where(cb.equal(root.join("inspectedPort").get("elementId"), inspectedId));

        Query q= this.em.createQuery(criteria);

        @SuppressWarnings("unchecked")
        List<InspectionHookEntity> results = q.getResultList();

        return results;
    }
 
Example 19
Project: osc-core   File: DeploymentSpecEntityMgr.java   Source Code and License Vote up 3 votes
public static List<DeploymentSpec> listDeploymentSpecByProjectId(EntityManager em, String projectId) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<DeploymentSpec> query = cb.createQuery(DeploymentSpec.class);

    Root<DeploymentSpec> root = query.from(DeploymentSpec.class);

    query = query.select(root).distinct(true)
            .where(cb.equal(root.get("projectId"), projectId));

    return em.createQuery(query).getResultList();
}
 
Example 20
Project: osc-core   File: DistributedApplianceEntityMgr.java   Source Code and License Vote up 3 votes
public static List<DistributedAppliance> listActiveByManagerConnector(EntityManager em, ApplianceManagerConnector mc) {
    CriteriaBuilder cb = em.getCriteriaBuilder();

    CriteriaQuery<DistributedAppliance> query = cb.createQuery(DistributedAppliance.class);

    Root<DistributedAppliance> root = query.from(DistributedAppliance.class);

    query = query.select(root).distinct(true)
            .where(cb.equal(root.get("markedForDeletion"), false),
                    cb.equal(root.get("applianceManagerConnector"), mc));

    return em.createQuery(query).getResultList();
}