Java Code Examples for javax.persistence.criteria.CriteriaBuilder#or()

The following examples show how to use javax.persistence.criteria.CriteriaBuilder#or() . 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: ActionListLike.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Wo> list(Business business, Wi wi) throws Exception {
	List<Wo> wos = new ArrayList<>();
	if (StringUtils.isEmpty(wi.getKey())) {
		return wos;
	}
	List<String> roleIds = business.expendGroupRoleToRole(wi.getGroupList(), wi.getRoleList());
	String str = StringUtils.lowerCase(StringTools.escapeSqlLikeKey(wi.getKey()));
	EntityManager em = business.entityManagerContainer().get(Role.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Role> cq = cb.createQuery(Role.class);
	Root<Role> root = cq.from(Role.class);
	Predicate p = cb.like(cb.lower(root.get(Role_.name)), "%" + str + "%", StringTools.SQL_ESCAPE_CHAR);
	p = cb.or(p, cb.like(cb.lower(root.get(Role_.pinyin)), str + "%", StringTools.SQL_ESCAPE_CHAR));
	p = cb.or(p, cb.like(cb.lower(root.get(Role_.pinyinInitial)), str + "%", StringTools.SQL_ESCAPE_CHAR));
	p = cb.or(p, cb.like(cb.lower(root.get(Role_.distinguishedName)), str + "%", StringTools.SQL_ESCAPE_CHAR));
	if (ListTools.isNotEmpty(roleIds)) {
		p = cb.and(p, root.get(Role_.id).in(roleIds));
	}
	List<Role> os = em.createQuery(cq.select(root).where(p)).getResultList();
	wos = Wo.copier.copy(os);
	wos = business.role().sort(wos);
	return wos;
}
 
Example 2
Source File: PersonFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
public Person getWithCredential(String value) throws Exception {
	Person person = this.pick(value);
	if (null == person) {
		EntityManager em = this.entityManagerContainer().get(Person.class);
		CriteriaBuilder cb = em.getCriteriaBuilder();
		CriteriaQuery<Person> cq = cb.createQuery(Person.class);
		Root<Person> root = cq.from(Person.class);
		Predicate p = cb.equal(root.get(Person_.mobile), value);
		p = cb.or(p, cb.equal(root.get(Person_.qq), value));
		p = cb.or(p, cb.equal(root.get(Person_.mail), value));
		p = cb.or(p, cb.equal(root.get(Person_.weixin), value));
		List<Person> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
		if (os.size() == 1) {
			person = os.get(0);
		}
	}
	return person;
}
 
Example 3
Source File: BBSSubjectInfoFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 查询指定的版块内时间范围内发表的主题数量
 * @param sectionId
 * @param todayStartTime
 * @param todayEndTime
 * @param queryMainSection  是否也查询主版块是sectionId的数据
 * @return
 * @throws Exception 
 */
public Long countSubjectByDate(String sectionId, Date todayStartTime, Date todayEndTime, boolean queryMainSection) throws Exception {
	if( StringUtils.isEmpty( sectionId ) ){
		throw new Exception("sectionId is null");
	}
	if( todayStartTime == null ) {
		todayStartTime = new DateOperation().getTodayStartTime();
	}
	if( todayEndTime == null ) {
		todayEndTime = new DateOperation().getTodayEndTime();
	}
	EntityManager em = this.entityManagerContainer().get(BBSSubjectInfo.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Long> cq = cb.createQuery(Long.class);
	Root<BBSSubjectInfo> root = cq.from( BBSSubjectInfo.class );
	Predicate p = cb.equal( root.get( BBSSubjectInfo_.sectionId ), sectionId );
	if( queryMainSection ) {
		p = cb.or( p, cb.equal( root.get( BBSSubjectInfo_.mainSectionId ), sectionId ));
	}
	Predicate p_time = cb.between( root.get( BBSSubjectInfo_.createTime ), todayStartTime, todayEndTime ) ;
	p = cb.and( p, p_time );
	cq.select( cb.count( root ) );
	return em.createQuery(cq.where(p)).getSingleResult();
}
 
Example 4
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 5
Source File: ActionClean.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<String> list(Business business, Boolean cleanWork, Boolean cleanWorkCompleted, Boolean cleanCms)
		throws Exception {
	EntityManager em = business.entityManagerContainer().get(Entry.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Entry> root = cq.from(Entry.class);
	Predicate p = cb.disjunction();
	if (BooleanUtils.isTrue(cleanWork)) {
		p = cb.or(p, cb.equal(root.get(Entry_.type), Entry.TYPE_WORK));
	}
	if (BooleanUtils.isTrue(cleanWorkCompleted)) {
		p = cb.or(p, cb.equal(root.get(Entry_.type), Entry.TYPE_WORKCOMPLETED));
	}
	if (BooleanUtils.isTrue(cleanCms)) {
		p = cb.or(p, cb.equal(root.get(Entry_.type), Entry.TYPE_CMS));
	}
	cq.select(root.get(Entry_.id)).where(p);
	List<String> os = em.createQuery(cq).setMaxResults(BATCHSIZE).getResultList();
	return os;
}
 
Example 6
Source File: AppInfoFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<String> listAppIdsWithOutAppType() throws Exception {
	EntityManager em = this.entityManagerContainer().get(AppInfo.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<AppInfo> root = cq.from(AppInfo.class);
	Predicate p = cb.isNull( root.get(AppInfo_.appType) );
	p = cb.or( p, cb.equal( root.get(AppInfo_.appType), ""));
	p = cb.or( p, cb.equal( root.get(AppInfo_.appType), "未分类"));
	cq.select(root.get(AppInfo_.id));
	return em.createQuery(cq.where(p)).getResultList();
}
 
Example 7
Source File: DropSpecification.java    From mojito with Apache License 2.0 5 votes vote down vote up
/**
 * A {@link Specification} to filter Drops that have been canceled or not.
 *
 * @param canceled {@code true} to get Drops that have been canceled,
 * {@code false} to get Drops that have not been canceled
 *
 * @return {@link Specification}
 */
public static SingleParamSpecification<Drop> isCanceled(final Boolean canceled) {
    return new SingleParamSpecification<Drop>(canceled) {
        @Override
        public Predicate toPredicate(Root<Drop> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
            if (canceled) {
                return builder.isTrue(root.get(Drop_.canceled));
            } else {
                return builder.or(builder.isNull(root.get(Drop_.canceled)),
                       builder.isFalse(root.get(Drop_.canceled)));
            }
        }
    };
}
 
Example 8
Source File: LikeSpecification.java    From jpa-spec with MIT License 5 votes vote down vote up
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
    From from = getRoot(property, root);
    String field = getProperty(property);
    if (patterns.length == 1) {
        return cb.like(from.get(field), patterns[0]);
    }
    Predicate[] predicates = new Predicate[patterns.length];
    for (int i = 0; i < patterns.length; i++) {
        predicates[i] = cb.like(from.get(field), patterns[i]);
    }
    return cb.or(predicates);
}
 
Example 9
Source File: ActionDelete.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private void removeMemberOfUnitController(Business business, Person person) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Unit.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Unit> cq = cb.createQuery(Unit.class);
	Root<Unit> root = cq.from(Unit.class);
	Predicate p = cb.isMember(person.getId(), root.get(Unit_.controllerList));
	p = cb.or(cb.isMember(person.getId(), root.get(Unit_.inheritedControllerList)));
	List<Unit> os = em.createQuery(cq.select(root).where(p).distinct(true)).getResultList();
	for (Unit o : os) {
		o.getControllerList().remove(person.getId());
		o.getInheritedControllerList().remove(person.getId());
	}
}
 
Example 10
Source File: OkrCenterWorkInfoFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 根据身份名称,从中心工作信息中查询与该身份有关的所有信息列表
 * @param identity
 * @param recordId 
 * @return
 * @throws Exception
 */
public List<OkrCenterWorkInfo> listErrorIdentitiesInCenterInfo( String identity, String recordId ) throws Exception {
	EntityManager em = this.entityManagerContainer().get(OkrCenterWorkInfo.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<OkrCenterWorkInfo> cq = cb.createQuery( OkrCenterWorkInfo.class );
	Root<OkrCenterWorkInfo> root = cq.from( OkrCenterWorkInfo.class );
	Predicate p = cb.isNotNull(root.get( OkrCenterWorkInfo_.id ));
	
	if( recordId != null && !recordId.isEmpty() && !"all".equals( recordId ) ){
		p = cb.and( p, cb.equal( root.get( OkrCenterWorkInfo_.id ), recordId ) );
	}
	
	Predicate p_creatorIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.creatorIdentity ));
	p_creatorIdentity = cb.and( p_creatorIdentity, cb.equal( root.get( OkrCenterWorkInfo_.creatorIdentity ), identity ) );
	
	Predicate p_deployerIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.deployerIdentity ));
	p_deployerIdentity = cb.and( p_deployerIdentity, cb.equal( root.get( OkrCenterWorkInfo_.deployerIdentity ), identity ) );
	
	Predicate p_reportAuditLeaderIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList ));
	p_reportAuditLeaderIdentity = cb.and( p_reportAuditLeaderIdentity,cb.isMember(identity, root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList )));
	
	Predicate p_auditLeaderIdentity = cb.isNotNull(root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList ));
	p_auditLeaderIdentity = cb.and( p_auditLeaderIdentity, cb.isMember( identity, root.get( OkrCenterWorkInfo_.reportAuditLeaderIdentityList ) ) );
	
	Predicate p_identity = cb.or( p_creatorIdentity, p_deployerIdentity, p_reportAuditLeaderIdentity, p_auditLeaderIdentity );
		
	p = cb.and( p, p_identity );
	
	return em.createQuery(cq.where(p)).getResultList();
}
 
Example 11
Source File: PersonFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public String getWithCredential(String credential) throws Exception {
	EntityManager em = this.entityManagerContainer().get(Person.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Person> root = cq.from(Person.class);
	Predicate p = cb.equal(root.get(Person_.name), credential);
	p = cb.or(p, cb.equal(root.get(Person_.distinguishedName), credential));
	p = cb.or(p, cb.equal(root.get(Person_.unique), credential));
	p = cb.or(p, cb.equal(root.get(Person_.id), credential));
	p = cb.or(p, cb.equal(root.get(Person_.mail), credential));
	p = cb.or(p, cb.equal(root.get(Person_.qq), credential));
	p = cb.or(p, cb.equal(root.get(Person_.weixin), credential));
	p = cb.or(p, cb.equal(root.get(Person_.mobile), credential));
	p = cb.or(p, cb.equal(root.get(Person_.employee), credential));
	p = cb.or(p, cb.equal(root.get(Person_.open1Id), credential));
	p = cb.or(p, cb.equal(root.get(Person_.open2Id), credential));
	p = cb.or(p, cb.equal(root.get(Person_.open3Id), credential));
	p = cb.or(p, cb.equal(root.get(Person_.open4Id), credential));
	p = cb.or(p, cb.equal(root.get(Person_.open5Id), credential));
	cq.select(root.get(Person_.id));
	List<String> list = em.createQuery(cq.where(p).distinct(true)).getResultList();
	if (list.size() == 1) {
		return list.get(0);
	} else {
		return null;
	}
}
 
Example 12
Source File: AppInfoFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public List<String> listLike(String keyStr) throws Exception {
	String str = keyStr.replaceAll("_", "\\\\_");
	str = str.replaceAll("%", "\\\\%");
	str = str.toLowerCase();
	EntityManager em = this.entityManagerContainer().get(AppInfo.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<AppInfo> root = cq.from(AppInfo.class);
	Predicate p = cb.like(root.get(AppInfo_.appName), "%" + str + "%", '\\');
	p = cb.or(p, cb.like(root.get(AppInfo_.appAlias), str + "%", '\\'));
	cq.select(root.get(AppInfo_.id)).where(p);
	return em.createQuery(cq).setMaxResults(200).getResultList();
}
 
Example 13
Source File: BBSReplyInfoFactory.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
public Long countBySectionId( String sectionId ) throws Exception {
	EntityManager em = this.entityManagerContainer().get( BBSReplyInfo.class );
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Long> cq = cb.createQuery(Long.class);
	Root<BBSReplyInfo> root = cq.from( BBSReplyInfo.class);
	Predicate p = cb.equal( root.get( BBSReplyInfo_.mainSectionId ), sectionId );
	p = cb.or( p, cb.equal( root.get( BBSReplyInfo_.sectionId ), sectionId ) );
	cq.select( cb.count( root ) );		
	return em.createQuery(cq.where(p)).getSingleResult();
}
 
Example 14
Source File: BoardSpecification.java    From springboot-vue.js-bbs with Apache License 2.0 5 votes vote down vote up
public static Specification<Board> findByAll(final String keyword) {
    return (Root<Board> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
        String keywordLCase = keyword.toLowerCase();
        query.distinct(true);
        return cb.or(
                cb.like(cb.lower(root.get(Pagination.FilterType.USER.toString().toLowerCase()).get("name")),
                        "%" + keywordLCase + "%"),
                cb.like(cb.lower(root.get(Pagination.FilterType.TITLE.toString().toLowerCase())),
                        "%" + keywordLCase + "%"),
                cb.like(cb.lower(root.get(Pagination.FilterType.CONTENT.toString().toLowerCase())),
                        "%" + keywordLCase + "%")
        );
    };
}
 
Example 15
Source File: ActionHasRole.java    From o2oa with GNU Affero General Public License v3.0 5 votes vote down vote up
private Wo get(Business business, Wi wi) throws Exception {
	Wo wo = new Wo();
	wo.setValue(false);
	if (StringUtils.isEmpty(wi.getPerson()) || ListTools.isEmpty(wi.getRoleList())) {
		return wo;
	}
	Person person = business.person().pick(wi.getPerson());
	if (null == person) {
		return wo;
	}
	List<Role> roles = business.role().pick(wi.getRoleList());
	if (ListTools.isEmpty(roles)) {
		return wo;
	}
	List<String> groupIds = new ArrayList<>();
	groupIds.addAll(business.group().listSupNestedWithPerson(person.getId()));
	groupIds = ListTools.trim(groupIds, true, true);
	EntityManager em = business.entityManagerContainer().get(Role.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<Role> root = cq.from(Role.class);
	Predicate p = cb.isMember(person.getId(), root.get(Role_.personList));
	p = cb.or(p, root.get(Role_.groupList).in(groupIds));
	List<String> os = em.createQuery(cq.select(root.get(Role_.id)).where(p).distinct(true)).getResultList();
	boolean value = ListTools.containsAny(os,
			ListTools.extractProperty(roles, JpaObject.id_FIELDNAME, String.class, true, true));
	wo.setValue(value);
	return wo;
}
 
Example 16
Source File: BusinessObjectDataDaoImpl.java    From herd with Apache License 2.0 4 votes vote down vote up
/**
 * Adds retention expiration filter to the query predicate.
 *
 * @param builder the criteria builder
 * @param businessObjectDataEntityRoot the root business object data entity
 * @param businessObjectFormatEntityJoin the join with the business object format table
 * @param businessObjectDefinitionEntity the business object definition entity
 * @param predicate the query predicate to be updated, not null
 *
 * @return the updated query predicate
 */
private Predicate addRetentionExpirationFilterToPredicate(CriteriaBuilder builder, Root<BusinessObjectDataEntity> businessObjectDataEntityRoot,
    Join<BusinessObjectDataEntity, BusinessObjectFormatEntity> businessObjectFormatEntityJoin,
    BusinessObjectDefinitionEntity businessObjectDefinitionEntity, Predicate predicate)
{
    // Get latest versions of all business object formats that registered with the business object definition.
    List<BusinessObjectFormatEntity> businessObjectFormatEntities =
        businessObjectFormatDao.getLatestVersionBusinessObjectFormatsByBusinessObjectDefinition(businessObjectDefinitionEntity);

    // Create a result predicate to join all retention expiration predicates created per selected business object formats.
    Predicate businessObjectDefinitionRetentionExpirationPredicate = null;

    // Get the current database timestamp to be used to select expired business object data per BDATA_RETENTION_DATE retention type.
    Timestamp currentTimestamp = getCurrentTimestamp();

    // Create a predicate for each business object format with the retention information.
    for (BusinessObjectFormatEntity businessObjectFormatEntity : businessObjectFormatEntities)
    {
        if (businessObjectFormatEntity.getRetentionType() != null)
        {
            // Create a retention expiration predicate for this business object format.
            Predicate businessObjectFormatRetentionExpirationPredicate = null;

            if (StringUtils.equals(businessObjectFormatEntity.getRetentionType().getCode(), RetentionTypeEntity.BDATA_RETENTION_DATE))
            {
                // Select business object data that has expired per its explicitly configured retention expiration date.
                businessObjectFormatRetentionExpirationPredicate =
                    builder.lessThan(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.retentionExpiration), currentTimestamp);
            }
            else if (StringUtils.equals(businessObjectFormatEntity.getRetentionType().getCode(), RetentionTypeEntity.PARTITION_VALUE) &&
                businessObjectFormatEntity.getRetentionPeriodInDays() != null)
            {
                // Compute the retention expiration date and convert it to the date format to match against partition values.
                String retentionExpirationDate = DateFormatUtils
                    .format(DateUtils.addDays(new Date(), -1 * businessObjectFormatEntity.getRetentionPeriodInDays()), DEFAULT_SINGLE_DAY_DATE_MASK);

                // Create a predicate to compare business object data primary partition value against the retention expiration date.
                businessObjectFormatRetentionExpirationPredicate =
                    builder.lessThan(businessObjectDataEntityRoot.get(BusinessObjectDataEntity_.partitionValue), retentionExpirationDate);
            }

            // If it was initialize, complete processing of retention expiration predicate for this business object format.
            if (businessObjectFormatRetentionExpirationPredicate != null)
            {
                // Update the predicate to match this business object format w/o version.
                businessObjectFormatRetentionExpirationPredicate = builder.and(businessObjectFormatRetentionExpirationPredicate, builder
                    .equal(builder.upper(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.usage)),
                        businessObjectFormatEntity.getUsage().toUpperCase()));
                businessObjectFormatRetentionExpirationPredicate = builder.and(businessObjectFormatRetentionExpirationPredicate,
                    builder.equal(businessObjectFormatEntityJoin.get(BusinessObjectFormatEntity_.fileType), businessObjectFormatEntity.getFileType()));

                // Add this business object format specific retention expiration predicate to other
                // retention expiration predicates created for the specified business object definition.
                if (businessObjectDefinitionRetentionExpirationPredicate == null)
                {
                    businessObjectDefinitionRetentionExpirationPredicate = businessObjectFormatRetentionExpirationPredicate;
                }
                else
                {
                    businessObjectDefinitionRetentionExpirationPredicate =
                        builder.or(businessObjectDefinitionRetentionExpirationPredicate, businessObjectFormatRetentionExpirationPredicate);
                }
            }
        }
    }

    // Fail if no retention expiration predicates got created per specified business objject definition.
    Assert.notNull(businessObjectDefinitionRetentionExpirationPredicate, String
        .format("Business object definition with name \"%s\" and namespace \"%s\" has no business object formats with supported retention type.",
            businessObjectDefinitionEntity.getName(), businessObjectDefinitionEntity.getNamespace().getCode()));

    // Add created business object definition retention expiration predicate to the query predicate passed to this method and return the result.
    return builder.and(predicate, businessObjectDefinitionRetentionExpirationPredicate);
}
 
Example 17
Source File: CategoryInfoFactory.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 根据权限查询用户可以发布文档的分类ID列表(根据权限, 不检测allPeopleView和allPeoplePublish)
 * 可管理的分类也属于可发布的分类
 * @param personName
 * @param unitNames
 * @param groupNames
 * @param inAppInfoIds  - 需要限定的栏目ID列表
 * @param inCategoryIds  - 栏目ID的最大范围
 * @param excludCategoryIds - 需要排除的栏目ID
 * @return
 * @throws Exception 
 */
public List<String> listPublishableCategoryInfoIdsWithPermission(String personName, List<String> unitNames,
		List<String> groupNames, List<String> inAppInfoIds, List<String> inCategoryIds,
		List<String> excludCategoryIds, String documentType, Integer maxCount ) throws Exception {
	EntityManager em = this.entityManagerContainer().get(CategoryInfo.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<CategoryInfo> root = cq.from(CategoryInfo.class);
	
	Predicate p = null;
	Predicate p_filter = null;
	//限定栏目范围
	if( ListTools.isNotEmpty( inAppInfoIds )) {
		p_filter = root.get( CategoryInfo_.appId ).in( inAppInfoIds );
	}
	//限定范围
	if( ListTools.isNotEmpty( inCategoryIds )) {
		if( p_filter == null ) {
			p_filter = root.get( CategoryInfo_.id ).in( inCategoryIds );
		}else {
			p_filter = cb.and( p_filter, root.get( CategoryInfo_.id ).in( inCategoryIds ));
		}
	}
	//排除指定的ID列表
	if( ListTools.isNotEmpty( excludCategoryIds )) {
		if( p_filter == null ) {
			p_filter = cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds ));
		}else {
			p_filter = cb.and( p_filter, cb.not( root.get( CategoryInfo_.id ).in( excludCategoryIds )));
		}
	}		
	Predicate p_permission = null;
	if( StringUtils.isNotEmpty( personName )) {
		//可以管理的栏目,肯定可以发布信息
		p_permission = cb.isMember( personName, root.get( CategoryInfo_.manageablePersonList ));	
		p_permission = cb.or( p_permission, cb.isMember( personName, root.get( CategoryInfo_.publishablePersonList )));			
	}
	if( ListTools.isNotEmpty( unitNames )) {
		if( p_permission == null  ) {
			p_permission = root.get( CategoryInfo_.publishableUnitList).in(unitNames);
		}else {
			p_permission = cb.or( p_permission,  root.get( CategoryInfo_.publishableUnitList).in(unitNames));
		}
	}
	if( ListTools.isNotEmpty( groupNames )) {
		if( p_permission == null  ) {
			p_permission = root.get( CategoryInfo_.publishableGroupList).in(groupNames);
		}else {
			p_permission = cb.or( p_permission,  root.get( CategoryInfo_.publishableGroupList).in(groupNames));
		}
	}
	
	//使用新的条件将两个条件组合起来
	if( p_filter != null ) {
		p = p_filter;
	}
	if( p != null ) {
		if( p_permission != null ) {
			p = cb.and(p, p_permission);
		}
	}else {
		if( p_permission != null ) {
			p = p_permission;
		}
	}
	if( StringUtils.isNotEmpty( documentType) && !"全部".equals(documentType)&& !"all".equalsIgnoreCase(documentType)) {
		p = cb.and( p, cb.equal( root.get( CategoryInfo_.documentType), documentType));
	}
	cq.select(root.get( CategoryInfo_.id ));
	return em.createQuery( cq.where( p ) ).setMaxResults(maxCount).getResultList();
}
 
Example 18
Source File: CmsPermissionService.java    From o2oa with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * 查询用户有权限发布文档的所有栏目ID列表( 不检测allPeopleView, with List copy )
 * 
 * @param personName
 * @param unitNames
 * @param groupNames
 * @param inAppInfoIds
 * @param excludAppInfoIds
 * @return
 * @throws Exception
 */
private List<String> listPublishableAppIdsInPermission(EntityManagerContainer emc, String personName,
		List<String> unitNames, List<String> groupNames, List<String> inAppInfoIds, List<String> excludAppInfoIds,
		String documentType, Integer maxCount) throws Exception {
	List<String> appInfoIds = null;
	List<String> appInfoIds_out = new ArrayList<>();
	EntityManager em = emc.get(AppInfo.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<String> cq = cb.createQuery(String.class);
	Root<AppInfo> root = cq.from(AppInfo.class);

	Predicate p = null;
	// 限定范围
	if (ListTools.isNotEmpty(inAppInfoIds)) {
		p = CriteriaBuilderTools.predicate_and(cb, p, cb.and(p, root.get(AppInfo.id_FIELDNAME).in(inAppInfoIds)));
	}
	// 排除指定的ID列表
	if (ListTools.isNotEmpty(excludAppInfoIds)) {
		p = CriteriaBuilderTools.predicate_and(cb, p, cb.not(root.get(AppInfo.id_FIELDNAME).in(excludAppInfoIds)));
	}
	if (StringUtils.isNotEmpty(documentType) && !"全部".equals(documentType)
			&& !"all".equalsIgnoreCase(documentType)) {
		p = CriteriaBuilderTools.predicate_and(cb, p,
				cb.equal(root.get(AppInfo.documentType_FIELDNAME), documentType));
	}

	Predicate p_permission = null;
	if (StringUtils.isNotEmpty(personName)) {
		// 可以管理的栏目,肯定可以发布信息
		p_permission = cb.isMember(personName, root.get(AppInfo.manageablePersonList_FIELDNAME));
		p_permission = cb.or(p_permission,
				cb.isMember(personName, root.get(AppInfo.publishablePersonList_FIELDNAME)));
	}
	if (ListTools.isNotEmpty(unitNames)) {
		p_permission = cb.or(p_permission, root.get(AppInfo.publishableUnitList_FIELDNAME).in(unitNames));
	}
	if (ListTools.isNotEmpty(groupNames)) {
		p_permission = cb.or(p_permission, root.get(AppInfo.publishableGroupList_FIELDNAME).in(groupNames));
	}

	p = CriteriaBuilderTools.predicate_and(cb, p, p_permission);
	cq.select(root.get(AppInfo.id_FIELDNAME));
	appInfoIds = em.createQuery(cq.where(p)).setMaxResults(maxCount).getResultList();
	if (appInfoIds == null) {
		appInfoIds = new ArrayList<>();
	}
	appInfoIds_out.addAll(appInfoIds);
	appInfoIds_out = excludListContent(appInfoIds_out, excludAppInfoIds);
	return appInfoIds_out;
}
 
Example 19
Source File: JpaUtils.java    From WeBASE-Collect-Bee with Apache License 2.0 4 votes vote down vote up
public static Predicate orTogether(List<Predicate> ps, CriteriaBuilder cb) {
    return cb.or(ps.toArray(new Predicate[0]));
}
 
Example 20
Source File: JpaQueryUtils.java    From we-cmdb with Apache License 2.0 4 votes vote down vote up
public static void applyFilter(CriteriaBuilder cb, CriteriaQuery query, List<Filter> filters, Map<String, Expression> selectionMap, Map<String, Class<?>> fieldTypeMap, FilterRelationship filterRs, List<Predicate> predicates,
        Predicate accessControlPredicate) {
    if (predicates == null) {
        predicates = new LinkedList<>();
    }
    for (Filter filter : filters) {
        Expression filterExpr = validateFilterName(selectionMap, filter);
        switch (FilterOperator.fromCode(filter.getOperator())) {
        case In:
            processInOperator(cb, predicates, filter, filterExpr);
            break;
        case Contains:
            processContainsOperator(cb, predicates, filter, filterExpr);
            break;
        case Equal:
            processEqualsOperator(cb, predicates, filter, filterExpr);
            break;
        case Greater:
            processGreaterOperator(cb, predicates, filter, filterExpr);
            break;
        case GreaterEqual:
            processGreaterEqualOperator(cb, predicates, filter, filterExpr);
            break;
        case Less:
            processLessOperator(cb, predicates, filter, filterExpr);
            break;
        case LessEqual:
            processLessEqualOperator(cb, predicates, filter, filterExpr);
            break;
        case NotEqual:
            processNotEqualsOperator(cb, predicates, filter, filterExpr);
            break;
        case NotNull:
            predicates.add(cb.isNotNull(filterExpr));
            break;
        case Null:
            predicates.add(cb.isNull(filterExpr));
            break;
        case LIKE:
            predicates.add(cb.like(cb.upper(filterExpr), "%" + (String) filter.getValue().toString().toUpperCase() + "%"));
            break;
        case NotEmpty:
            filter.setValue("");
            processNotEqualsOperator(cb, predicates, filter, filterExpr);
            predicates.add(cb.isNotNull(filterExpr));
            break;
        case Empty:
            filter.setValue("");
            processNotEqualsOperator(cb, predicates, filter, filterExpr);
            break;
        default:
            throw new InvalidArgumentException(String.format("Filter operator [%s] is unsupportted.", filter.getOperator()));
        }
    }

    Predicate mergedFilterPredicate;
    if (predicates.size() > 0) {
        if (FilterRelationship.Or.equals(filterRs)) {
            mergedFilterPredicate = cb.or(predicates.toArray(new Predicate[0]));
        } else {
            mergedFilterPredicate = cb.and(predicates.toArray(new Predicate[0]));
        }
    } else {
        mergedFilterPredicate = cb.conjunction();
    }

    if (accessControlPredicate != null) {
        query.where(cb.and(mergedFilterPredicate, accessControlPredicate));
    } else {
        query.where(mergedFilterPredicate);
    }
}