Java Code Examples for javax.persistence.criteria.CriteriaQuery#multiselect()

The following examples show how to use javax.persistence.criteria.CriteriaQuery#multiselect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DefaultIssueManager.java    From onedev with MIT License 8 votes vote down vote up
@Sessional
@Override
public Collection<MilestoneAndState> queryMilestoneAndStates(Project project, Collection<Milestone> milestones) {
	CriteriaBuilder builder = getSession().getCriteriaBuilder();
	CriteriaQuery<MilestoneAndState> criteriaQuery = builder.createQuery(MilestoneAndState.class);
	Root<Issue> root = criteriaQuery.from(Issue.class);
	criteriaQuery.multiselect(
			root.get(Issue.PROP_MILESTONE).get(Milestone.PROP_ID), 
			root.get(Issue.PROP_STATE));
	
	List<Predicate> milestonePredicates = new ArrayList<>();
	for (Milestone milestone: milestones) 
		milestonePredicates.add(builder.equal(root.get(Issue.PROP_MILESTONE), milestone));
	
	criteriaQuery.where(builder.and(
			builder.equal(root.get(Issue.PROP_PROJECT), project),
			builder.or(milestonePredicates.toArray(new Predicate[0]))));
	
	return getSession().createQuery(criteriaQuery).getResultList();
}
 
Example 2
Source File: DefaultBuildManager.java    From onedev with MIT License 7 votes vote down vote up
private CriteriaQuery<Object[]> buildQueryOfStreamPrevios(Build build, Status status, String...fields) {
	CriteriaBuilder builder = getSession().getCriteriaBuilder();
	CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
	Root<Build> root = query.from(Build.class);
	
	List<Predicate> predicates = new ArrayList<>();
	predicates.add(builder.equal(root.get("project"), build.getProject()));
	predicates.add(builder.equal(root.get("jobName"), build.getJobName()));
	if (status != null)
		predicates.add(builder.equal(root.get("status"), status));
	predicates.add(builder.lessThan(root.get("number"), build.getNumber()));
	query.where(predicates.toArray(new Predicate[0]));
	List<Selection<?>> selections = new ArrayList<>();
	for (String field: fields)
		selections.add(root.get(field));
	query.multiselect(selections);
	
	return query;
}
 
Example 3
Source File: ProductMilestoneProviderImpl.java    From pnc with Apache License 2.0 6 votes vote down vote up
private CriteriaQuery<Tuple> milestoneInfoQuery(CriteriaBuilder cb, Set<Integer> milestoneIds) {
    CriteriaQuery<Tuple> query = cb.createTupleQuery();

    Root<org.jboss.pnc.model.ProductMilestone> milestone = query.from(org.jboss.pnc.model.ProductMilestone.class);
    Root<ProductRelease> release = query.from(ProductRelease.class);
    Path<ProductVersion> version = milestone.get(ProductMilestone_.productVersion);
    Path<Product> product = version.get(ProductVersion_.product);
    query.multiselect(
            product.get(Product_.id),
            product.get(Product_.name),
            version.get(ProductVersion_.id),
            version.get(ProductVersion_.version),
            milestone.get(ProductMilestone_.id),
            milestone.get(ProductMilestone_.version),
            milestone.get(ProductMilestone_.endDate),
            release.get(ProductRelease_.id),
            release.get(ProductRelease_.version),
            release.get(ProductRelease_.releaseDate));
    query.where(
            cb.and(cb.equal(release.get(ProductRelease_.productMilestone), milestone)),
            milestone.get(ProductMilestone_.id).in(milestoneIds));
    query.orderBy(cb.desc(milestone.get(ProductMilestone_.endDate)), cb.desc(milestone.get(ProductMilestone_.id)));
    return query;
}
 
Example 4
Source File: TestCriteriaTuples.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void selectTuples() {
	log.info("... selectTuples ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> q = cb.createTupleQuery();
	Root<Author> author = q.from(Author.class);
	q.multiselect(author.get(Author_.firstName).alias("firstName"), 
					author.get(Author_.lastName).alias("lastName"));

	TypedQuery<Tuple> query = em.createQuery(q);
	List<Tuple> authorNames = query.getResultList();

	for (Tuple authorName : authorNames) {
		log.info(authorName.get("firstName") + " "
				+ authorName.get("lastName"));
	}

	em.getTransaction().commit();
	em.close();
}
 
Example 5
Source File: TestCriteriaFunction.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void callSizeFunction() {
	log.info("... callSizeFunction ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createTupleQuery();
	Root<Author> root = cq.from(Author.class);
	cq.multiselect(root, cb.size(root.get(Author_.books)));
	cq.groupBy(root.get(Author_.id));
	
	TypedQuery<Tuple> q = em.createQuery(cq);
	List<Tuple> results = q.getResultList();
	
	for (Tuple r :  results) {
		log.info(r.get(0) + " wrote " +  r.get(1) + " books.");
	}

	em.getTransaction().commit();
	em.close();
}
 
Example 6
Source File: TestMetamodel.java    From HibernateTips with MIT License 6 votes vote down vote up
@Test
public void getBooks() {
	log.info("... getBooks ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createTupleQuery();
	Root<Book> root = cq.from(Book.class);
	cq.multiselect(root.get(Book_.title), root.get(Book_.publishingDate));
			
	List<Tuple> results = em.createQuery(cq).getResultList();
	
	for (Tuple r : results) {
		log.info(r.get(0) + " was published on " + r.get(1));
	}
	
	em.getTransaction().commit();
	em.close();
}
 
Example 7
Source File: GenericRepositoryImpl.java    From HA-DB with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private <S> S aggregate(CriteriaBuilder builder, CriteriaQuery<S> query, Root<E> root, Specification<E> spec, List<Selection<?>> selectionList, LockModeType lockMode) {
	if (selectionList != null) {
		Predicate predicate = spec.toPredicate(root, query, builder);
		if (predicate != null) {
			query.where(predicate);
		}
		query.multiselect(selectionList);
		return (S) em.createQuery(query).setLockMode(lockMode).getSingleResult();
	}
	return null;
}
 
Example 8
Source File: ProductRepository.java    From tutorials with MIT License 5 votes vote down vote up
public List<Object[]> findAllIdNameUnitPriceUsingCriteriaQueryMultiselect() {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
    Root<Product> product = query.from(Product.class);
    query.multiselect(product.get("id"), product.get("name"), product.get("unitPrice"));
    List<Object[]> resultList = entityManager.createQuery(query).getResultList();
    return resultList;
}
 
Example 9
Source File: StorageUnitNotificationRegistrationDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public List<NotificationRegistrationKey> getStorageUnitNotificationRegistrationKeysByNamespace(String namespace)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the storage unit notification registration.
    Root<StorageUnitNotificationRegistrationEntity> businessObjectDataNotificationEntityRoot =
        criteria.from(StorageUnitNotificationRegistrationEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageUnitNotificationRegistrationEntity, NamespaceEntity> namespaceEntityJoin =
        businessObjectDataNotificationEntityRoot.join(StorageUnitNotificationRegistrationEntity_.namespace);

    // Get the columns.
    Path<String> notificationRegistrationNamespaceColumn = namespaceEntityJoin.get(NamespaceEntity_.code);
    Path<String> notificationRegistrationNameColumn = businessObjectDataNotificationEntityRoot.get(StorageUnitNotificationRegistrationEntity_.name);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntityJoin.get(NamespaceEntity_.code)), namespace.toUpperCase());

    // Add the select clause.
    criteria.multiselect(notificationRegistrationNamespaceColumn, notificationRegistrationNameColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // Add the order by clause.
    criteria.orderBy(builder.asc(notificationRegistrationNameColumn));

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the list of keys from the returned tuples.
    return getNotificationRegistrationKeys(tuples, notificationRegistrationNamespaceColumn, notificationRegistrationNameColumn);
}
 
Example 10
Source File: BusinessObjectDataNotificationRegistrationDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public List<NotificationRegistrationKey> getBusinessObjectDataNotificationRegistrationKeysByNamespace(String namespace)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object data notification registration.
    Root<BusinessObjectDataNotificationRegistrationEntity> businessObjectDataNotificationEntity =
        criteria.from(BusinessObjectDataNotificationRegistrationEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataNotificationRegistrationEntity, NamespaceEntity> namespaceEntity =
        businessObjectDataNotificationEntity.join(BusinessObjectDataNotificationRegistrationEntity_.namespace);

    // Get the columns.
    Path<String> notificationRegistrationNamespaceColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> notificationRegistrationNameColumn = businessObjectDataNotificationEntity.get(BusinessObjectDataNotificationRegistrationEntity_.name);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), namespace.toUpperCase());

    // Add the select clause.
    criteria.multiselect(notificationRegistrationNamespaceColumn, notificationRegistrationNameColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // Add the order by clause.
    criteria.orderBy(builder.asc(notificationRegistrationNameColumn));

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the list of keys from the returned tuples.
    return getNotificationRegistrationKeys(tuples, notificationRegistrationNamespaceColumn, notificationRegistrationNameColumn);
}
 
Example 11
Source File: HibernateGenericStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Count number of objects based on given parameters
 *
 * @param parameters JpaQueryParameters
 * @return number of objects
 */
protected final Long getCount( CriteriaBuilder builder, JpaQueryParameters<T> parameters )
{
    CriteriaQuery<Long> query = builder.createQuery( Long.class );

    Root<T> root = query.from( getClazz() );

    List<Function<Root<T>, Predicate>> predicateProviders = parameters.getPredicates();

    List<Function<Root<T>, Expression<Long>>> countExpressions = parameters.getCountExpressions();

    if ( !countExpressions.isEmpty() )
    {
        if ( countExpressions.size() > 1 )
        {
            query.multiselect( countExpressions.stream().map( c -> c.apply( root ) ).collect( Collectors.toList() ) );
        }
        else
        {
            query.select( countExpressions.get( 0 ).apply( root ) );
        }
    }
    else
    {
        query.select( parameters.isUseDistinct() ? builder.countDistinct( root ) : builder.count( root ) );
    }

    if ( !predicateProviders.isEmpty() )
    {
        List<Predicate> predicates = predicateProviders.stream().map( t -> t.apply( root ) ).collect( Collectors.toList() );
        query.where( predicates.toArray( new Predicate[0] ) );
    }

    return getSession().createQuery( query )
        .setHint( QueryHints.CACHEABLE, parameters.isCacheable( cacheable ) )
        .getSingleResult();
}
 
Example 12
Source File: Query.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private void fillAttributeSelectEntriesDocument(EntityManagerContainer emc, List<String> docIds,
		List<SelectEntry> selectEntries, Table table) throws Exception {
	EntityManager em = emc.get(Document.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<Document> root = cq.from(Document.class);
	List<Selection<?>> selections = new ArrayList<>();
	Selection<Object> selectionDoc = null;
	for (SelectEntry en : selectEntries) {
		if (en.available()) {
			if (StringUtils.equals(Document.id_FIELDNAME, en.getAttribute())) {
				selectionDoc = root.get(Document.id_FIELDNAME).alias(en.getColumn());
				selections.add(selectionDoc);
			} else {
				selections.add(root.get(en.getAttribute()).alias(en.getColumn()));
			}
		}
	}
	if (selectionDoc == null) {
		selectionDoc = root.get(Document.id_FIELDNAME);
		cq.multiselect(ListTools.add(selections, true, false, selectionDoc));
	} else {
		cq.multiselect(selections);
	}
	cq.where(root.get(Document.id_FIELDNAME).in(docIds));
	List<Tuple> tuples = em.createQuery(cq).getResultList();
	for (Tuple tuple : tuples) {
		Object job = tuple.get(selectionDoc);
		Row row = table.get(job.toString());
		for (Selection<?> selection : selections) {
			/* 前面已经填充了默认值,如果是null那么跳过这个值 */
			if (null != tuple.get(selection)) {
				row.put(selection.getAlias(), tuple.get(selection));
			}
		}
	}
}
 
Example 13
Source File: ActionListAllPersonName.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
protected List<Tuple> execute(Business business, WrapInStringList wrapIn) throws Exception {
	EntityManagerContainer emc = business.entityManagerContainer();
	EntityManager em = emc.get(Person.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Tuple> cq = cb.createQuery(Tuple.class);
	Root<Person> root = cq.from(Person.class);
	List<Selection<?>> selections = new ArrayList<>();
	for (String str : wrapIn.getValueList()) {
		selections.add(root.get(str));
	}
	cq.multiselect(selections);
	List<Tuple> wraps = em.createQuery(cq).getResultList();
	return wraps;
}
 
Example 14
Source File: ProductRepository.java    From tutorials with MIT License 5 votes vote down vote up
public List<Object[]> findCountByCategoryUsingCriteriaBuilder() {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);
    Root<Product> product = query.from(Product.class);
    query.multiselect(product.get("category"), builder.count(product));
    query.groupBy(product.get("category"));
    List<Object[]> resultList = entityManager.createQuery(query).getResultList();
    return resultList;
}
 
Example 15
Source File: EnumInfoRepositoryImpl.java    From we-cmdb with Apache License 2.0 4 votes vote down vote up
private void selectForEnumInfo(CriteriaQuery query, Map<String, Expression> selectionMap) {
    query.multiselect(selectionMap.get(SEL_CAT_ID), selectionMap.get(SEL_CAT_NAME), selectionMap.get(SEL_CODE_ID), selectionMap.get(SEL_CODE), selectionMap.get(SEL_VALUE), selectionMap.get(SEL_GROUP_CODE_ID),
            selectionMap.get(SEL_GROUP_CODE), selectionMap.get(SEL_GROUP_NAME), selectionMap.get(SEL_DESCRIPTION));
}
 
Example 16
Source File: BusinessObjectDataDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public Map<BusinessObjectDataEntity, StoragePolicyEntity> getBusinessObjectDataEntitiesMatchingStoragePolicies(
    StoragePolicyPriorityLevel storagePolicyPriorityLevel, List<String> supportedBusinessObjectDataStatuses, int storagePolicyTransitionMaxAllowedAttempts,
    int startPosition, int maxResult)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object data along with the storage policy.
    Root<BusinessObjectDataEntity> businessObjectDataEntityRoot = criteria.from(BusinessObjectDataEntity.class);
    Root<StoragePolicyEntity> storagePolicyEntityRoot = criteria.from(StoragePolicyEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDataEntity, StorageUnitEntity> storageUnitEntityJoin = businessObjectDataEntityRoot.join(BusinessObjectDataEntity_.storageUnits);
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin =
        businessObjectDataEntityRoot.join(BusinessObjectDataEntity_.businessObjectFormat);

    // Create main query restrictions based on the specified parameters.
    List<Predicate> predicates = new ArrayList<>();

    // Add restriction on business object definition.
    predicates.add(storagePolicyPriorityLevel.isBusinessObjectDefinitionIsNull() ?
        builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.businessObjectDefinitionId)) : builder
        .equal(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.businessObjectDefinitionId),
            storagePolicyEntityRoot.get(StoragePolicyEntity_.businessObjectDefinitionId)));

    // Add restriction on business object format usage.
    predicates.add(storagePolicyPriorityLevel.isUsageIsNull() ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.usage)) : builder
        .equal(builder.upper(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
            builder.upper(storagePolicyEntityRoot.get(StoragePolicyEntity_.usage))));

    // Add restriction on business object format file type.
    predicates.add(storagePolicyPriorityLevel.isFileTypeIsNull() ? builder.isNull(storagePolicyEntityRoot.get(StoragePolicyEntity_.fileType)) : builder
        .equal(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.fileTypeCode),
            storagePolicyEntityRoot.get(StoragePolicyEntity_.fileTypeCode)));

    // Add restriction on storage policy filter storage.
    predicates.add(builder.equal(storageUnitEntityJoin.get(StorageUnitEntity_.storageName), storagePolicyEntityRoot.get(StoragePolicyEntity_.storageName)));

    // Add restriction on storage policy latest version flag.
    predicates.add(builder.isTrue(storagePolicyEntityRoot.get(StoragePolicyEntity_.latestVersion)));

    // Add restriction on storage policy status.
    predicates.add(builder.equal(storagePolicyEntityRoot.get(StoragePolicyEntity_.statusCode), StoragePolicyStatusEntity.ENABLED));

    // Add restriction on supported business object data statuses.
    predicates.add(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.statusCode).in(supportedBusinessObjectDataStatuses));

    // Add restrictions as per storage policy transition type.
    predicates
        .add(builder.equal(storagePolicyEntityRoot.get(StoragePolicyEntity_.storagePolicyTransitionTypeCode), StoragePolicyTransitionTypeEntity.GLACIER));
    predicates.add(storageUnitEntityJoin.get(StorageUnitEntity_.statusCode)
        .in(Lists.newArrayList(StorageUnitStatusEntity.ENABLED, StorageUnitStatusEntity.ARCHIVING)));

    // If specified, add restriction on maximum allowed attempts for a storage policy transition.
    if (storagePolicyTransitionMaxAllowedAttempts > 0)
    {
        predicates.add(builder.or(builder.isNull(storageUnitEntityJoin.get(StorageUnitEntity_.storagePolicyTransitionFailedAttempts)), builder
            .lessThan(storageUnitEntityJoin.get(StorageUnitEntity_.storagePolicyTransitionFailedAttempts), storagePolicyTransitionMaxAllowedAttempts)));
    }

    // Order the results by business object data "created on" value.
    Order orderByCreatedOn = builder.asc(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.createdOn));

    // Add the select clause to the main query.
    criteria.multiselect(businessObjectDataEntityRoot, storagePolicyEntityRoot);

    // Add the where clause to the main query.
    criteria.where(predicates.toArray(new Predicate[] {}));

    // Add the order by clause to the main query.
    criteria.orderBy(orderByCreatedOn);

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).setFirstResult(startPosition).setMaxResults(maxResult).getResultList();

    // Populate the result map from the returned tuples (i.e. 1 tuple for each row).
    Map<BusinessObjectDataEntity, StoragePolicyEntity> result = new LinkedHashMap<>();
    for (Tuple tuple : tuples)
    {
        // Since multiple storage policies can contain identical filters, we add the below check to select each business object data instance only once.
        if (!result.containsKey(tuple.get(businessObjectDataEntityRoot)))
        {
            result.put(tuple.get(businessObjectDataEntityRoot), tuple.get(storagePolicyEntityRoot));
        }
    }

    return result;
}
 
Example 17
Source File: BusinessObjectFormatDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public List<BusinessObjectFormatKey> getBusinessObjectFormatsWithFilters(BusinessObjectDefinitionKey businessObjectDefinitionKey,
    String businessObjectFormatUsage, boolean latestBusinessObjectFormatVersion)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object format.
    Root<BusinessObjectFormatEntity> businessObjectFormatEntity = criteria.from(BusinessObjectFormatEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity =
        businessObjectFormatEntity.join(BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity.join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity.join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Expression<Integer> maxBusinessObjectFormatVersionExpression =
        builder.max(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion));

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction =
        builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), businessObjectDefinitionKey.getNamespace().toUpperCase());
    queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
        businessObjectDefinitionKey.getBusinessObjectDefinitionName().toUpperCase()));

    // Add the business object format usage where parameter is not empty
    if (StringUtils.isNotEmpty(businessObjectFormatUsage))
    {
        queryRestriction = builder.and(queryRestriction,
            builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)), businessObjectFormatUsage.toUpperCase()));
    }

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn, businessObjectFormatUsageColumn, fileTypeCodeColumn,
        latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression : businessObjectFormatVersionColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // If only the latest (maximum) business object format versions to be returned, create and apply the group by clause.
    if (latestBusinessObjectFormatVersion)
    {
        List<Expression<?>> grouping = new ArrayList<>();
        grouping.add(namespaceCodeColumn);
        grouping.add(businessObjectDefinitionNameColumn);
        grouping.add(businessObjectFormatUsageColumn);
        grouping.add(fileTypeCodeColumn);
        criteria.groupBy(grouping);
    }

    // Add the order by clause.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(businessObjectFormatUsageColumn));
    orderBy.add(builder.asc(fileTypeCodeColumn));
    if (!latestBusinessObjectFormatVersion)
    {
        orderBy.add(builder.asc(businessObjectFormatVersionColumn));
    }
    criteria.orderBy(orderBy);

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectFormatKey> businessObjectFormatKeys = new ArrayList<>();
    for (Tuple tuple : tuples)
    {
        BusinessObjectFormatKey businessObjectFormatKey = new BusinessObjectFormatKey();
        businessObjectFormatKeys.add(businessObjectFormatKey);
        businessObjectFormatKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectFormatKey.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
        businessObjectFormatKey.setBusinessObjectFormatUsage(tuple.get(businessObjectFormatUsageColumn));
        businessObjectFormatKey.setBusinessObjectFormatFileType(tuple.get(fileTypeCodeColumn));
        businessObjectFormatKey.setBusinessObjectFormatVersion(
            tuple.get(latestBusinessObjectFormatVersion ? maxBusinessObjectFormatVersionExpression : businessObjectFormatVersionColumn));
    }

    return businessObjectFormatKeys;
}
 
Example 18
Source File: CustomDdlDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public List<CustomDdlKey> getCustomDdls(BusinessObjectFormatKey businessObjectFormatKey)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object format.
    Root<CustomDdlEntity> customDdlEntity = criteria.from(CustomDdlEntity.class);

    // Join to the other tables we can filter on.
    Join<CustomDdlEntity, BusinessObjectFormatEntity> businessObjectFormatEntity = customDdlEntity.join(CustomDdlEntity_.businessObjectFormat);
    Join<BusinessObjectFormatEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = businessObjectFormatEntity.join(
        BusinessObjectFormatEntity_.businessObjectDefinition);
    Join<BusinessObjectFormatEntity, FileTypeEntity> fileTypeEntity = businessObjectFormatEntity.join(BusinessObjectFormatEntity_.fileType);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity.join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name);
    Path<String> businessObjectFormatUsageColumn = businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage);
    Path<String> fileTypeCodeColumn = fileTypeEntity.get(FileTypeEntity_.code);
    Path<Integer> businessObjectFormatVersionColumn = businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion);
    Path<String> customDdlNameColumn = customDdlEntity.get(CustomDdlEntity_.customDdlName);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate queryRestriction = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), businessObjectFormatKey.getNamespace()
        .toUpperCase());
    queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name)),
        businessObjectFormatKey.getBusinessObjectDefinitionName().toUpperCase()));
    queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.usage)),
        businessObjectFormatKey.getBusinessObjectFormatUsage().toUpperCase()));
    queryRestriction = builder.and(queryRestriction, builder.equal(builder.upper(fileTypeEntity.get(FileTypeEntity_.code)), businessObjectFormatKey
        .getBusinessObjectFormatFileType().toUpperCase()));
    queryRestriction = builder.and(queryRestriction, builder.equal(businessObjectFormatEntity.get(BusinessObjectFormatEntity_.businessObjectFormatVersion),
        businessObjectFormatKey.getBusinessObjectFormatVersion()));

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn, businessObjectFormatUsageColumn, fileTypeCodeColumn,
        businessObjectFormatVersionColumn, customDdlNameColumn);

    // Add the where clause.
    criteria.where(queryRestriction);

    // Add the order by clause.
    criteria.orderBy(builder.asc(customDdlNameColumn));

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<CustomDdlKey> customDdlKeys = new ArrayList<>();
    for (Tuple tuple : tuples)
    {
        CustomDdlKey customDdlKey = new CustomDdlKey();
        customDdlKeys.add(customDdlKey);
        customDdlKey.setNamespace(tuple.get(namespaceCodeColumn));
        customDdlKey.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
        customDdlKey.setBusinessObjectFormatUsage(tuple.get(businessObjectFormatUsageColumn));
        customDdlKey.setBusinessObjectFormatFileType(tuple.get(fileTypeCodeColumn));
        customDdlKey.setBusinessObjectFormatVersion(tuple.get(businessObjectFormatVersionColumn));
        customDdlKey.setCustomDdlName(tuple.get(customDdlNameColumn));
    }

    return customDdlKeys;
}
 
Example 19
Source File: BusinessObjectDefinitionDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public List<BusinessObjectDefinitionKey> getBusinessObjectDefinitionKeysByNamespace(String namespaceCode)
{
    // Create the criteria builder and a tuple style criteria query.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Tuple> criteria = builder.createTupleQuery();

    // The criteria root is the business object definition.
    Root<BusinessObjectDefinitionEntity> businessObjectDefinitionEntity = criteria.from(BusinessObjectDefinitionEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntity = businessObjectDefinitionEntity.join(BusinessObjectDefinitionEntity_.namespace);

    // Get the columns.
    Path<String> namespaceCodeColumn = namespaceEntity.get(NamespaceEntity_.code);
    Path<String> businessObjectDefinitionNameColumn = businessObjectDefinitionEntity.get(BusinessObjectDefinitionEntity_.name);

    // Add the select clause.
    criteria.multiselect(namespaceCodeColumn, businessObjectDefinitionNameColumn);

    // If namespace code is specified, add the where clause.
    if (StringUtils.isNotBlank(namespaceCode))
    {
        criteria.where(builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), namespaceCode.toUpperCase()));
    }

    // Add the order by clause.
    if (StringUtils.isNotBlank(namespaceCode))
    {
        criteria.orderBy(builder.asc(businessObjectDefinitionNameColumn));
    }
    else
    {
        criteria.orderBy(builder.asc(businessObjectDefinitionNameColumn), builder.asc(namespaceCodeColumn));
    }

    // Run the query to get a list of tuples back.
    List<Tuple> tuples = entityManager.createQuery(criteria).getResultList();

    // Populate the "keys" objects from the returned tuples (i.e. 1 tuple for each row).
    List<BusinessObjectDefinitionKey> businessObjectDefinitionKeys = new ArrayList<>();
    for (Tuple tuple : tuples)
    {
        BusinessObjectDefinitionKey businessObjectDefinitionKey = new BusinessObjectDefinitionKey();
        businessObjectDefinitionKeys.add(businessObjectDefinitionKey);
        businessObjectDefinitionKey.setNamespace(tuple.get(namespaceCodeColumn));
        businessObjectDefinitionKey.setBusinessObjectDefinitionName(tuple.get(businessObjectDefinitionNameColumn));
    }

    return businessObjectDefinitionKeys;
}
 
Example 20
Source File: CiServiceImpl.java    From we-cmdb with Apache License 2.0 4 votes vote down vote up
private List doIntegrateQuery(IntegrationQueryDto intQueryDto, QueryRequest intQueryReq, boolean isSelRowCount, List<FieldInfo> selectedFields) {

        PriorityEntityManager priEntityManager = getEntityManager();
        EntityManager entityManager = priEntityManager.getEntityManager();

        try {
            CriteriaBuilder cb = entityManager.getCriteriaBuilder();
            CriteriaQuery query = cb.createQuery();

            Map<String, FieldInfo> selFieldMap = new LinkedHashMap<>();

            boolean enableBiz = false;

            // TODO, enable Bizkey & status logic should be removed
            enableBiz = checkBizEnable(intQueryReq);
            logger.info("enable biz:{}", enableBiz);
            buildIntQuery(null, null, intQueryDto, query, selFieldMap, enableBiz, null);
            validateIntQueryFilter(intQueryReq, selFieldMap, enableBiz);
            List<Expression> selections = new LinkedList<>();

            if (isSelRowCount) {
                Expression root = selFieldMap.get("root").getExpression();
                query.select(cb.count(root));
            } else {
                selFieldMap.remove("root");
                for (Map.Entry<String, FieldInfo> kv : selFieldMap.entrySet()) {
                    if (isRequestField(intQueryReq, kv)) {
                        if (enableBiz) {
                            if (kv.getKey().endsWith(".biz_key") || kv.getKey().endsWith(".state")) {
                                continue;
                            }
                        }
                        if (kv.getKey().startsWith(ACCESS_CONTROL_ATTRIBUTE_PREFIX)) {
                            continue;
                        }

                        if (kv.getKey().endsWith(".guid") || kv.getKey().endsWith(".r_guid")) {
                            if(!isRequestExplicitly(intQueryReq, (Map.Entry<String, FieldInfo>) kv)) {
                                continue;
                            }
                        }

/*
                        if(!isRequestField(intQueryReq,kv)){
                            continue;
                        }
*/

                        selectedFields.add(kv.getValue());
                        if (!selections.contains(kv.getValue().getExpression())) {
                            selections.add(kv.getValue().getExpression());
                        }
                    }
                }
                query.multiselect(selections);
            }

            Map<String, Expression> selectionMap = new HashMap<>();
            Map<String, Class<?>> fieldTypeMap = new HashMap<>();
            selFieldMap.forEach((k, v) -> {
                fieldTypeMap.put(k, v.getType());
                selectionMap.put(k, v.getExpression());
            });

            if (!isSelRowCount && intQueryReq.getSorting() != null) {
                JpaQueryUtils.applySorting(intQueryReq.getSorting(), cb, query, selectionMap);
            }

            // TODO: enable biz logic should be removed
            if (enableBiz) {
                processBizFilters(intQueryReq, selectionMap);
            }

            List<Predicate> predicates = buildHistoryDataControlPredicate(intQueryReq, cb, selectionMap);

            Predicate accessControlPredicate = buildAccessControlPredicate(cb, selFieldMap, selectionMap);

            JpaQueryUtils.applyFilter(cb, query, intQueryReq.getFilters(), selectionMap, fieldTypeMap, FilterRelationship.fromCode(intQueryReq.getFilterRs()), predicates, accessControlPredicate);

            TypedQuery typedQuery = entityManager.createQuery(query);
            if (!isSelRowCount && intQueryReq.isPaging()) {
                JpaQueryUtils.applyPaging(intQueryReq.isPaging(), intQueryReq.getPageable(), typedQuery);
            }

            List resultList = typedQuery.getResultList();

            return resultList;
        } finally {
            priEntityManager.close();
        }
    }