javax.persistence.criteria.Join Java Examples

The following examples show how to use javax.persistence.criteria.Join. 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: StorageFileDaoImpl.java    From herd with Apache License 2.0 11 votes vote down vote up
@Override
public StorageFileEntity getStorageFileByStorageNameAndFilePath(String storageName, String filePath)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<StorageFileEntity> criteria = builder.createQuery(StorageFileEntity.class);

    // The criteria root is the storage files.
    Root<StorageFileEntity> storageFileEntity = criteria.from(StorageFileEntity.class);

    // Join to the other tables we can filter on.
    Join<StorageFileEntity, StorageUnitEntity> storageUnitEntity = storageFileEntity.join(StorageFileEntity_.storageUnit);
    Join<StorageUnitEntity, StorageEntity> storageEntity = storageUnitEntity.join(StorageUnitEntity_.storage);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate filePathRestriction = builder.equal(storageFileEntity.get(StorageFileEntity_.path), filePath);
    Predicate storageNameRestriction = builder.equal(builder.upper(storageEntity.get(StorageEntity_.name)), storageName.toUpperCase());

    criteria.select(storageFileEntity).where(builder.and(filePathRestriction, storageNameRestriction));

    return executeSingleResultQuery(criteria,
        String.format("Found more than one storage file with parameters {storageName=\"%s\"," + " filePath=\"%s\"}.", storageName, filePath));
}
 
Example #2
Source File: HibernateCategoryOptionComboStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
@Override
public List<CategoryOptionCombo> getCategoryOptionCombosByGroupUid( String groupUid )
{
    CriteriaBuilder builder = getCriteriaBuilder();
    CriteriaQuery<CategoryOptionCombo> query = builder.createQuery( CategoryOptionCombo.class );
    Root<CategoryOptionCombo> root = query.from( CategoryOptionCombo.class );
    Join<Object, Object> joinCatOption = root.join( "categoryOptions", JoinType.INNER );
    Join<Object, Object> joinCatOptionGroup = joinCatOption.join( "groups", JoinType.INNER );
    query.where( builder.equal( joinCatOptionGroup.get( "uid" ), groupUid ) );
    return getSession().createQuery( query ).list();
}
 
Example #3
Source File: CommentRepositoryHibernate.java    From realworld-api-quarkus with MIT License 6 votes vote down vote up
@Override
public Optional<Comment> findComment(String slug, Long commentId, Long authorId) {

  CriteriaBuilder builder = getCriteriaBuilder();
  CriteriaQuery<Comment> criteriaQuery = getCriteriaQuery(builder);
  Root<Comment> comment = getRoot(criteriaQuery);

  Join<Comment, Article> article = comment.join("article");
  Join<Comment, User> author = comment.join("author");

  criteriaQuery.select(comment);
  criteriaQuery.where(
      builder.and(
          builder.equal(builder.upper(article.get("slug")), slug.toUpperCase().trim()),
          builder.equal(comment.get("id"), commentId),
          builder.equal(author.get("id"), authorId)));

  return Optional.ofNullable(getSingleResult(criteriaQuery));
}
 
Example #4
Source File: HibernateCategoryOptionGroupStore.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public List<CategoryOptionGroup> getCategoryOptionGroups( CategoryOptionGroupSet groupSet )
{
    CriteriaBuilder builder = getCriteriaBuilder();

    JpaQueryParameters<CategoryOptionGroup> parameters = newJpaParameters()
        .addPredicates( getSharingPredicates( builder ) )
        .addPredicate( root -> {
            Join<Object, Object> groupSets = root.join( "groupSets" );

            return builder.or( builder.equal( groupSets.get( "id" ) , groupSet.getId() ),
                                builder.isNull( groupSets.get( "id" ) ) );
        });

    return getList( builder, parameters );
}
 
Example #5
Source File: TagDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public TagEntity getTagByTagTypeAndDisplayName(String tagTypeCode, String displayName)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<TagEntity> criteria = builder.createQuery(TagEntity.class);

    // The criteria root is the tag entity.
    Root<TagEntity> tagEntityRoot = criteria.from(TagEntity.class);

    // Join on the other tables we can filter on.
    Join<TagEntity, TagTypeEntity> tagTypeEntityJoin = tagEntityRoot.join(TagEntity_.tagType);

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(builder.equal(builder.upper(tagTypeEntityJoin.get(TagTypeEntity_.code)), tagTypeCode.toUpperCase()));
    predicates.add(builder.equal(builder.upper(tagEntityRoot.get(TagEntity_.displayName)), displayName.toUpperCase()));

    // Add all clauses to the query.
    criteria.select(tagEntityRoot).where(builder.and(predicates.toArray(new Predicate[predicates.size()])));

    return executeSingleResultQuery(criteria,
        String.format("Found more than one tag with parameters {tagType=\"%s\", displayName=\"%s\"}.", tagTypeCode, displayName));
}
 
Example #6
Source File: FieldCriteria.java    From onedev with MIT License 6 votes vote down vote up
@Override
public final Predicate getPredicate(Root<Issue> root, CriteriaBuilder builder) {
	Join<?, ?> join = root.join(Issue.PROP_FIELDS, JoinType.LEFT);
	Predicate valuePredicate = getValuePredicate(join, builder);
	if (valuePredicate != null) {
		join.on(builder.and(
				builder.equal(join.get(IssueField.PROP_NAME), getFieldName()), 
				getValuePredicate(join, builder)));
		return join.isNotNull();
	} else {
		join.on(builder.and(
				builder.equal(join.get(IssueField.PROP_NAME), getFieldName()), 
				builder.or(builder.isNull(join.get(IssueField.PROP_VALUE)))));
		Join<?, ?> join2 = root.join(Issue.PROP_FIELDS, JoinType.LEFT);
		join2.on(builder.equal(join2.get(IssueField.PROP_NAME), getFieldName()));
		return builder.or(join.isNotNull(), join2.isNull());
	}
}
 
Example #7
Source File: OwnedByCriteria.java    From onedev with MIT License 6 votes vote down vote up
@Override
public Predicate getPredicate(Root<Project> root, CriteriaBuilder builder) {
	Join<?, ?> userAuthorizationJoin = root.join(Project.PROP_USER_AUTHORIZATIONS, JoinType.LEFT);

	userAuthorizationJoin.on(builder.and(
			builder.equal(userAuthorizationJoin.get(UserAuthorization.PROP_ROLE), Role.OWNER_ID), 
			builder.equal(userAuthorizationJoin.get(UserAuthorization.PROP_USER), user)));
	
	if (user.getGroups().isEmpty()) {
		return userAuthorizationJoin.isNotNull();
	} else {
		Join<?, ?> groupAuthorizationJoin = root.join(Project.PROP_GROUP_AUTHORIZATIONS, JoinType.LEFT);
		groupAuthorizationJoin.on(builder.and(
				builder.equal(groupAuthorizationJoin.get(GroupAuthorization.PROP_ROLE), Role.OWNER_ID), 
				groupAuthorizationJoin.get(GroupAuthorization.PROP_GROUP).in(user.getGroups())));
		return builder.or(userAuthorizationJoin.isNotNull(), groupAuthorizationJoin.isNotNull());
	}
}
 
Example #8
Source File: PasswordCredentialResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(DELETE)
public Void delete(UserPermissionPrincipal principal,
                   ActionRecord actionRecord,
                   RestContext context,
                   EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<PasswordCredential> query = cb.createQuery(PasswordCredential.class);
    Root<PasswordCredential> passwordCredentialRoot = query.from(PasswordCredential.class);
    Join<User, PasswordCredential> userRoot = passwordCredentialRoot.join("user");
    query.where(cb.equal(userRoot.get("name"), principal.getName()));
    EntityTransactionManager tx = new EntityTransactionManager(em);
    em.createQuery(query)
            .getResultStream()
            .findAny()
            .ifPresent(passwordCredential -> tx.required(() -> {
                em.remove(passwordCredential);
                config.getHookRepo().runHook(AFTER_DELETE_PASSWORD_CREDENTIAL, context);
            }));

    actionRecord.setActionType(ActionType.PASSWORD_DELETED);
    actionRecord.setActor(principal.getName());

    return null;
}
 
Example #9
Source File: JobDefinitionDaoImpl.java    From herd with Apache License 2.0 6 votes vote down vote up
@Override
public JobDefinitionEntity getJobDefinitionByAltKey(String namespace, String jobName)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<JobDefinitionEntity> criteria = builder.createQuery(JobDefinitionEntity.class);

    // The criteria root is the job definition.
    Root<JobDefinitionEntity> jobDefinition = criteria.from(JobDefinitionEntity.class);

    // Join to the other tables we can filter on.
    Join<JobDefinitionEntity, NamespaceEntity> namespaceJoin = jobDefinition.join(JobDefinitionEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    Predicate namespaceRestriction = builder.equal(builder.upper(namespaceJoin.get(NamespaceEntity_.code)), namespace.toUpperCase());
    Predicate jobNameRestriction = builder.equal(builder.upper(jobDefinition.get(JobDefinitionEntity_.name)), jobName.toUpperCase());

    criteria.select(jobDefinition).where(builder.and(namespaceRestriction, jobNameRestriction));

    return executeSingleResultQuery(criteria,
        String.format("Found more than one Activiti job definition with parameters {namespace=\"%s\", jobName=\"%s\"}.", namespace, jobName));
}
 
Example #10
Source File: QueryStructure.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings({ "unchecked" })
private void renderJoins(
		StringBuilder jpaqlQuery,
		RenderingContext renderingContext,
		Collection<Join<?,?>> joins) {
	if ( joins == null ) {
		return;
	}

	for ( Join join : joins ) {
		( (FromImplementor) join ).prepareAlias( renderingContext );
		jpaqlQuery.append( renderJoinType( join.getJoinType() ) )
				.append( ( (FromImplementor) join ).renderTableExpression( renderingContext ) );
		renderJoins( jpaqlQuery, renderingContext, join.getJoins() );
		renderFetches( jpaqlQuery, renderingContext, join.getFetches() );
	}
}
 
Example #11
Source File: RealmResource.java    From bouncr with Eclipse Public License 1.0 6 votes vote down vote up
@Decision(EXISTS)
public boolean exists(Parameters params, Application application, RestContext context, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Realm> query = cb.createQuery(Realm.class);
    Root<Realm> realmRoot = query.from(Realm.class);
    Join<Application, Realm> applicationJoin = realmRoot.join("application");
    query.where(cb.equal(realmRoot.get("name"), params.get("realmName")),
            cb.equal(applicationJoin.get("id"), application.getId()));

    Realm realm = em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultStream().findAny().orElse(null);
    if (realm != null) {
        context.putValue(realm);
    }
    return realm != null;
}
 
Example #12
Source File: AbstractJPATypedQueryVisitor.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Path<?> getNextPath(Path<?> element, String name, String postName,
    ClassValue cv, CollectionCheckInfo collSize) {
    final boolean isCollectionOrJoin = collSize == null
        && (cv.isCollection(name) || isJoinProperty(name) || existingCollectionInPostName(cv, postName))
        && (element == root || element instanceof Join);
    if (isCollectionOrJoin) {
        final Path<?> path = getExistingJoinProperty((From<?, ?>)element, name);
        if (path != null) {
            return path;
        }
        return element == root ? root.join(name) : ((Join<?, ?>)element).join(name);
    }
    return element.get(name);
}
 
Example #13
Source File: BusinessObjectDefinitionSubjectMatterExpertDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public BusinessObjectDefinitionSubjectMatterExpertEntity getBusinessObjectDefinitionSubjectMatterExpertByKey(
    BusinessObjectDefinitionSubjectMatterExpertKey key)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDefinitionSubjectMatterExpertEntity> criteria =
        builder.createQuery(BusinessObjectDefinitionSubjectMatterExpertEntity.class);

    // The criteria root is the business object definition subject matter expert.
    Root<BusinessObjectDefinitionSubjectMatterExpertEntity> businessObjectDefinitionSubjectMatterExpertEntityRoot =
        criteria.from(BusinessObjectDefinitionSubjectMatterExpertEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionSubjectMatterExpertEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntityJoin =
        businessObjectDefinitionSubjectMatterExpertEntityRoot.join(BusinessObjectDefinitionSubjectMatterExpertEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntityJoin =
        businessObjectDefinitionEntityJoin.join(BusinessObjectDefinitionEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(builder.equal(builder.upper(namespaceEntityJoin.get(NamespaceEntity_.code)), key.getNamespace().toUpperCase()));
    predicates.add(builder.equal(builder.upper(businessObjectDefinitionEntityJoin.get(BusinessObjectDefinitionEntity_.name)),
        key.getBusinessObjectDefinitionName().toUpperCase()));
    predicates.add(builder
        .equal(builder.upper(businessObjectDefinitionSubjectMatterExpertEntityRoot.get(BusinessObjectDefinitionSubjectMatterExpertEntity_.userId)),
            key.getUserId().toUpperCase()));

    // Add the clauses for the query.
    criteria.select(businessObjectDefinitionSubjectMatterExpertEntityRoot).where(builder.and(predicates.toArray(new Predicate[predicates.size()])));

    // Execute the query and return the results.
    return executeSingleResultQuery(criteria, String.format(
        "Found more than one business object definition subject matter expert instance with parameters {namespace=\"%s\", " +
            "businessObjectDefinitionName=\"%s\", userId=\"%s\"}.", key.getNamespace(), key.getBusinessObjectDefinitionName(), key.getUserId()));
}
 
Example #14
Source File: EmrServiceTest.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of {@link EmrClusterCreationLogEntity} objects for the given cluster namespace, cluster definition name, and EMR cluster name. All the
 * given parameters are case insensitive. The returned list's order is not guaranteed.
 *
 * @param namespace - EMR cluster namespace
 * @param definitionName - EMR cluster definition name
 * @param clusterName - EMR cluster name
 *
 * @return list of EMR cluster creation logs
 */
protected List<EmrClusterCreationLogEntity> getEmrClusterCreationLogEntities(String namespace, String definitionName, String clusterName)
{
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<EmrClusterCreationLogEntity> query = builder.createQuery(EmrClusterCreationLogEntity.class);
    Root<EmrClusterCreationLogEntity> emrClusterCreationLogEntity = query.from(EmrClusterCreationLogEntity.class);
    Join<?, NamespaceEntity> namespaceEntity = emrClusterCreationLogEntity.join(EmrClusterCreationLogEntity_.namespace);
    Predicate namespacePredicate = builder.equal(builder.upper(namespaceEntity.get(NamespaceEntity_.code)), namespace.toUpperCase());
    Predicate definitionNamePredicate =
        builder.equal(builder.upper(emrClusterCreationLogEntity.get(EmrClusterCreationLogEntity_.emrClusterDefinitionName)), definitionName.toUpperCase());
    Predicate clusterNamePredicate =
        builder.equal(builder.upper(emrClusterCreationLogEntity.get(EmrClusterCreationLogEntity_.emrClusterName)), clusterName.toUpperCase());
    query.select(emrClusterCreationLogEntity).where(builder.and(namespacePredicate, definitionNamePredicate, clusterNamePredicate));
    return entityManager.createQuery(query).getResultList();
}
 
Example #15
Source File: BusinessObjectDefinitionTagDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public BusinessObjectDefinitionTagEntity getBusinessObjectDefinitionTagByKey(BusinessObjectDefinitionTagKey businessObjectDefinitionTagKey)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<BusinessObjectDefinitionTagEntity> criteria = builder.createQuery(BusinessObjectDefinitionTagEntity.class);

    // The criteria root is the business object definition tag.
    Root<BusinessObjectDefinitionTagEntity> businessObjectDefinitionTagEntityRoot = criteria.from(BusinessObjectDefinitionTagEntity.class);

    // Join to the other tables we can filter on.
    Join<BusinessObjectDefinitionTagEntity, BusinessObjectDefinitionEntity> businessObjectDefinitionEntityJoin =
        businessObjectDefinitionTagEntityRoot.join(BusinessObjectDefinitionTagEntity_.businessObjectDefinition);
    Join<BusinessObjectDefinitionEntity, NamespaceEntity> namespaceEntityJoin =
        businessObjectDefinitionEntityJoin.join(BusinessObjectDefinitionEntity_.namespace);
    Join<BusinessObjectDefinitionTagEntity, TagEntity> tagEntityJoin = businessObjectDefinitionTagEntityRoot.join(BusinessObjectDefinitionTagEntity_.tag);
    Join<TagEntity, TagTypeEntity> tagTypeEntityJoin = tagEntityJoin.join(TagEntity_.tagType);

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    predicates.add(builder.equal(builder.upper(namespaceEntityJoin.get(NamespaceEntity_.code)),
        businessObjectDefinitionTagKey.getBusinessObjectDefinitionKey().getNamespace().toUpperCase()));
    predicates.add(builder.equal(builder.upper(businessObjectDefinitionEntityJoin.get(BusinessObjectDefinitionEntity_.name)),
        businessObjectDefinitionTagKey.getBusinessObjectDefinitionKey().getBusinessObjectDefinitionName().toUpperCase()));
    predicates.add(builder
        .equal(builder.upper(tagTypeEntityJoin.get(TagTypeEntity_.code)), businessObjectDefinitionTagKey.getTagKey().getTagTypeCode().toUpperCase()));
    predicates
        .add(builder.equal(builder.upper(tagEntityJoin.get(TagEntity_.tagCode)), businessObjectDefinitionTagKey.getTagKey().getTagCode().toUpperCase()));

    // Add the clauses for the query.
    criteria.select(businessObjectDefinitionTagEntityRoot).where(builder.and(predicates.toArray(new Predicate[predicates.size()])));

    return executeSingleResultQuery(criteria, String.format(
        "Found more than one business object definition tag instance with parameters {namespace=\"%s\", businessObjectDefinitionName=\"%s\"," +
            " tagType=\"%s\", tagCode=\"%s\"}.", businessObjectDefinitionTagKey.getBusinessObjectDefinitionKey().getNamespace(),
        businessObjectDefinitionTagKey.getBusinessObjectDefinitionKey().getBusinessObjectDefinitionName(),
        businessObjectDefinitionTagKey.getTagKey().getTagTypeCode(), businessObjectDefinitionTagKey.getTagKey().getTagCode()));
}
 
Example #16
Source File: BranchStatisticSpecification.java    From mojito with Apache License 2.0 5 votes vote down vote up
public static SingleParamSpecification<BranchStatistic> branchNameEquals(final String branchName) {
    return new SingleParamSpecification<BranchStatistic>(branchName) {
        @Override
        public Predicate toPredicate(Root<BranchStatistic> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            Join<BranchStatistic, Branch> branchJoin = root.join(BranchStatistic_.branch, JoinType.LEFT);
            return builder.equal(branchJoin.get(Branch_.name), branchName);
        }
    };
}
 
Example #17
Source File: ProductMilestonePredicates.java    From pnc with Apache License 2.0 5 votes vote down vote up
public static Predicate<ProductMilestone> withProductVersionIdAndVersion(Integer productVersionId, String version) {
    return (root, query, cb) -> {
        Join<ProductMilestone, ProductVersion> productVersion = root.join(ProductMilestone_.productVersion);
        return cb.and(
                cb.equal(productVersion.get(ProductVersion_.id), productVersionId),
                cb.equal(root.get(ProductMilestone_.version), version));
    };
}
 
Example #18
Source File: GroupUsersResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(HANDLE_OK)
public List<User> list(Group group, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<User> query = cb.createQuery(User.class);
    Root<User> userRoot = query.from(User.class);
    Join<Group, User> groupsJoin = userRoot.join("groups");
    query.where(cb.equal(groupsJoin.get("id"), group.getId()));
    query.orderBy(cb.asc(userRoot.get("id")));
    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .getResultList();
}
 
Example #19
Source File: SignInService.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
public Map<String, List<String>> getPermissionsByRealm(User user) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<Assignment> assignmentCriteria = cb.createQuery(Assignment.class);
    Root<Assignment> assignmentRoot = assignmentCriteria.from(Assignment.class);
    Join<Group, Assignment> groupJoin = assignmentRoot.join("group");
    Join<User, Group> userJoin = groupJoin.join("users");
    assignmentRoot.fetch("role").fetch("permissions");
    assignmentCriteria.where(cb.equal(userJoin.get("id"), user.getId()));

    EntityGraph<Assignment> assignmentGraph = em.createEntityGraph(Assignment.class);
    assignmentGraph.addAttributeNodes("realm", "role");
    Subgraph<Role> roleGraph = assignmentGraph.addSubgraph("role");
    roleGraph.addAttributeNodes("permissions");
    Subgraph<Permission> permissionsGraph = roleGraph.addSubgraph("permissions");
    permissionsGraph.addAttributeNodes("name");

    return em.createQuery(assignmentCriteria)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setHint("javax.persistence.fetchgraph", assignmentGraph)
            .getResultStream()
            .collect(Collectors.groupingBy(Assignment::getRealm))
            .entrySet()
            .stream()
            .collect(Collectors.toMap(
                    e -> e.getKey().getId().toString(),
                    e -> new ArrayList<>(e.getValue().stream()
                            .flatMap(v -> v.getRole().getPermissions().stream())
                            .map(Permission::getName)
                            .collect(Collectors.toSet()))));
}
 
Example #20
Source File: CustomDdlDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public CustomDdlEntity getCustomDdlByKey(CustomDdlKey customDdlKey)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<CustomDdlEntity> criteria = builder.createQuery(CustomDdlEntity.class);

    // The criteria root is the custom DDL.
    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);

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

    // Add select and where clauses.
    criteria.select(customDdlEntity).where(queryRestriction);

    return executeSingleResultQuery(criteria, String.format("Found more than one custom DDL instance with parameters {businessObjectDefinitionName=\"%s\","
        + " businessObjectFormatUsage=\"%s\", businessObjectFormatFileType=\"%s\", businessObjectFormatVersion=\"%d\", customDdlName=\"%s\"}.", customDdlKey
            .getBusinessObjectDefinitionName(), customDdlKey.getBusinessObjectFormatUsage(), customDdlKey.getBusinessObjectFormatFileType(), customDdlKey
                .getBusinessObjectFormatVersion(), customDdlKey.getCustomDdlName()));
}
 
Example #21
Source File: UserSessionsResource.java    From bouncr with Eclipse Public License 1.0 5 votes vote down vote up
@Decision(HANDLE_OK)
public List<UserSession> handleOk(UserSessionSearchParams params, UserPermissionPrincipal principal, EntityManager em) {
    CriteriaBuilder cb = em.getCriteriaBuilder();
    CriteriaQuery<UserSession> query = cb.createQuery(UserSession.class);
    Root<UserSession> userSessionRoot = query.from(UserSession.class);
    Join<User, UserSession> userJoin = userSessionRoot.join("user");
    query.where(cb.equal(userJoin.get("id"), principal.getId()));
    query.orderBy(cb.asc(userSessionRoot.get("id")));

    return em.createQuery(query)
            .setHint("javax.persistence.cache.storeMode", CacheStoreMode.REFRESH)
            .setFirstResult(params.getOffset())
            .setMaxResults(params.getLimit())
            .getResultList();
}
 
Example #22
Source File: AbstractFromImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addJoin(Join<X, ?> join) {
	if ( joins == null ) {
		joins = new LinkedHashSet<Join<X, ?>>();
	}
	joins.add( join );
}
 
Example #23
Source File: AbstractFromImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void addJoin(Join<X, ?> join) {
	if ( joins == null ) {
		joins = new LinkedHashSet<Join<X, ?>>();
	}
	joins.add( join );
}
 
Example #24
Source File: JoinBuilder.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private Join joinSet(From path)
{
    if (joinType == null)
    {
        return path.join(set);
    }
    return path.join(set, joinType);
}
 
Example #25
Source File: CommandPredicates.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * Get a predicate using the specified parameters.
 *
 * @param root     The {@link Root} (from) for this query
 * @param cq       The {@link CriteriaQuery} instance this predicate is for
 * @param cb       The {@link CriteriaBuilder} for the query
 * @param name     The name of the command
 * @param user     The name of the user who created the command
 * @param statuses The status of the command
 * @param tags     The set of tags to search the command for
 * @return A {@link Predicate} object used for querying
 */
public static Predicate find(
    final Root<CommandEntity> root,
    final CriteriaQuery<?> cq,
    final CriteriaBuilder cb,
    @Nullable final String name,
    @Nullable final String user,
    @Nullable final Set<String> statuses,
    @Nullable final Set<TagEntity> tags
) {
    final List<Predicate> predicates = new ArrayList<>();
    if (StringUtils.isNotBlank(name)) {
        predicates.add(
            PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(CommandEntity_.name), name)
        );
    }
    if (StringUtils.isNotBlank(user)) {
        predicates.add(
            PredicateUtils.getStringLikeOrEqualPredicate(cb, root.get(CommandEntity_.user), user)
        );
    }
    if (statuses != null && !statuses.isEmpty()) {
        predicates.add(
            cb.or(
                statuses
                    .stream()
                    .map(status -> cb.equal(root.get(CommandEntity_.status), status))
                    .toArray(Predicate[]::new)
            )
        );
    }
    if (tags != null && !tags.isEmpty()) {
        final Join<CommandEntity, TagEntity> tagEntityJoin = root.join(CommandEntity_.tags);
        predicates.add(tagEntityJoin.in(tags));
        cq.groupBy(root.get(CommandEntity_.id));
        cq.having(cb.equal(cb.count(root.get(CommandEntity_.id)), tags.size()));
    }
    return cb.and(predicates.toArray(new Predicate[0]));
}
 
Example #26
Source File: NamespaceIamRoleAuthorizationDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public List<NamespaceIamRoleAuthorizationEntity> getNamespaceIamRoleAuthorizations(NamespaceEntity namespaceEntity)
{
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<NamespaceIamRoleAuthorizationEntity> query = criteriaBuilder.createQuery(NamespaceIamRoleAuthorizationEntity.class);
    Root<NamespaceIamRoleAuthorizationEntity> root = query.from(NamespaceIamRoleAuthorizationEntity.class);
    Join<NamespaceIamRoleAuthorizationEntity, NamespaceEntity> namespaceJoin = root.join(NamespaceIamRoleAuthorizationEntity_.namespace);
    if (namespaceEntity != null)
    {
        query.where(criteriaBuilder.equal(root.get(NamespaceIamRoleAuthorizationEntity_.namespace), namespaceEntity));
    }
    query.orderBy(criteriaBuilder.asc(namespaceJoin.get(NamespaceEntity_.code)), criteriaBuilder.asc(root.get(
        NamespaceIamRoleAuthorizationEntity_.iamRoleName)));
    return entityManager.createQuery(query).getResultList();
}
 
Example #27
Source File: PermissionRepository.java    From spring-boot-practice with Apache License 2.0 5 votes vote down vote up
default List<Permission> findAllByRoleId(Integer id) {
    return findAll((root, query, cb) -> {
        // In this pattern, you can set restriction conditions to association table rolePermission.
        Join rp = root.join("rolePermission");
        Join r = rp.join("role");
        return cb.equal(r.get("id"), id);
    });
}
 
Example #28
Source File: ParamCriteria.java    From onedev with MIT License 5 votes vote down vote up
@Override
public Predicate getPredicate(Root<Build> root, CriteriaBuilder builder) {
	Join<?, ?> join = root.join(Build.PROP_PARAMS, JoinType.LEFT);
	join.on(builder.and(
			builder.equal(join.get(BuildParam.PROP_NAME), name)),
			builder.equal(join.get(BuildParam.PROP_VALUE), value));
	return join.isNotNull();
}
 
Example #29
Source File: BaseObject.java    From activejpa with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
protected static <T extends Model, S extends Model> TypedQuery<S> createQuery(Class<T> entityType, String attribute, Class<S> attributeType, Filter filter) {
	CriteriaBuilder builder = getEntityManager().getCriteriaBuilder();
	CriteriaQuery<S> cQuery = builder.createQuery(attributeType);
	Root<T> root = cQuery.from(entityType);
	if (attribute != null) {
		Join join = root.join(attribute);
		cQuery.select(join);
	}
	filter.constructQuery(builder, cQuery, root);
	return createQuery(cQuery, filter);
}
 
Example #30
Source File: JobDefinitionDaoImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
@Override
public List<JobDefinitionEntity> getJobDefinitionsByFilter(Collection<String> namespaces, String jobName)
{
    // Create the criteria builder and the criteria.
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<JobDefinitionEntity> criteria = builder.createQuery(JobDefinitionEntity.class);

    // The criteria root is the job definition.
    Root<JobDefinitionEntity> jobDefinitionEntityRoot = criteria.from(JobDefinitionEntity.class);

    // Join to the other tables we can filter on.
    Join<JobDefinitionEntity, NamespaceEntity> namespaceEntityJoin = jobDefinitionEntityRoot.join(JobDefinitionEntity_.namespace);

    // Create the standard restrictions (i.e. the standard where clauses).
    List<Predicate> predicates = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(namespaces))
    {
        predicates.add(namespaceEntityJoin.get(NamespaceEntity_.code).in(namespaces));
    }
    if (StringUtils.isNotBlank(jobName))
    {
        predicates.add(builder.equal(builder.upper(jobDefinitionEntityRoot.get(JobDefinitionEntity_.name)), jobName.toUpperCase()));
    }

    // Order the results by namespace and job name.
    List<Order> orderBy = new ArrayList<>();
    orderBy.add(builder.asc(namespaceEntityJoin.get(NamespaceEntity_.code)));
    orderBy.add(builder.asc(jobDefinitionEntityRoot.get(JobDefinitionEntity_.name)));

    // Add the clauses for the query.
    criteria.select(jobDefinitionEntityRoot).where(builder.and(predicates.toArray(new Predicate[predicates.size()]))).orderBy(orderBy);

    // Execute the query and return the result list.
    return entityManager.createQuery(criteria).getResultList();
}