下面列出了怎么用javax.persistence.criteria.JoinType的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void resolvesJoinContainerWithJoinFetch() throws Exception {
MethodParameter param = MethodParameter.forExecutable(testMethod("testMethod_joinContainerWithJoinFetch"), 0);
NativeWebRequest req = mock(NativeWebRequest.class);
QueryContext queryCtx = new WebRequestQueryContext(req);
when(req.getParameterValues("path1")).thenReturn(new String[] { "value1" });
Specification<?> resolved = (Specification<?>) resolver.resolveArgument(param, null, req, null);
assertThat(innerSpecs(resolved))
.hasSize(2)
.contains(new Like<Object>(queryCtx, "path1", new String[] { "value1" }))
.contains(new Conjunction<Object>(
new net.kaczmarzyk.spring.data.jpa.domain.JoinFetch<Object>(new String[] { "fetch1" }, JoinType.LEFT),
new net.kaczmarzyk.spring.data.jpa.domain.JoinFetch<Object>(new String[] { "fetch2" }, JoinType.INNER)));
}
private Path<?> getJoinFieldPath(final Path<?> fieldPath, final String fieldNameSplit) {
if (fieldPath instanceof PluralJoin) {
final Join<Object, ?> join = (Join<Object, ?>) fieldPath;
final From<?, Object> joinParent = join.getParent();
final Optional<Join<Object, Object>> currentJoinOfType = findCurrentJoinOfType(join.getJavaType());
if (currentJoinOfType.isPresent() && isOrLevel) {
// remove the additional join and use the existing one
joinParent.getJoins().remove(join);
return currentJoinOfType.get();
} else {
final Join<Object, Object> newJoin = joinParent.join(fieldNameSplit, JoinType.LEFT);
addCurrentJoin(newJoin);
return newJoin;
}
}
return fieldPath;
}
@Override
public Expression<?> doJoin(MetaAttribute targetAttr, JoinType joinType, Expression<?> parent) {
if (targetAttr instanceof MetaComputedAttribute) {
MetaComputedAttribute computedAttr = (MetaComputedAttribute) targetAttr;
QuerydslExpressionFactory expressionFactory = (QuerydslExpressionFactory<?>) queryImpl.getComputedAttrs()
.get(computedAttr);
return expressionFactory.getExpression(parent, getQuery());
}
else {
Expression<Object> expression = QuerydslUtils.get(parent, targetAttr.getName());
querydslQuery.getMetadata().addJoin(QuerydslUtils.convertJoinType(joinType), expression);
return expression;
}
}
/**
* Find empty profiles with a HW address matching some of given HW addresses.
*
* @param hwAddrs the set of HW addresses
* @return the List of MinionServer with a HW address matching some of given HW addresses
*/
public static List<MinionServer> findEmptyProfilesByHwAddrs(Set<String> hwAddrs) {
if (hwAddrs.isEmpty()) {
return emptyList();
}
CriteriaBuilder builder = getSession().getCriteriaBuilder();
CriteriaQuery<MinionServer> query = builder.createQuery(MinionServer.class);
Root<MinionServer> root = query.distinct(true).from(MinionServer.class);
Join<MinionServer, NetworkInterface> nicJoin = root.join("networkInterfaces", JoinType.INNER);
Predicate hwAddrPredicate = nicJoin.get("hwaddr").in(hwAddrs);
query.where(hwAddrPredicate);
return getSession().createQuery(query).stream()
.filter(s -> s.hasEntitlement(EntitlementManager.BOOTSTRAP))
.collect(toList());
}
@Override
public Expression<?> doJoin(MetaAttribute targetAttr, JoinType joinType, Expression<?> parent) {
if (targetAttr instanceof MetaComputedAttribute) {
MetaComputedAttribute computedAttr = (MetaComputedAttribute) targetAttr;
QuerydslExpressionFactory expressionFactory = (QuerydslExpressionFactory<?>) queryImpl.getComputedAttrs()
.get(computedAttr);
return expressionFactory.getExpression(parent, getQuery());
}
else {
Expression<Object> expression = QuerydslUtils.get(parent, targetAttr.getName());
querydslQuery.getMetadata().addJoin(QuerydslUtils.convertJoinType(joinType), expression);
return expression;
}
}
@Test
public void testOneRelatedEntityOrder() {
// per default will do left join
assertEquals(5, builder()
.addSortBy(Arrays.asList(TestEntity.ATTR_oneRelatedValue), Direction.DESC).buildExecutor().getResultList()
.size());
assertEquals((Long) 0L,
builder().setJoinType(Arrays.asList(TestEntity.ATTR_oneRelatedValue), JoinType.INNER)
.addSortBy(Arrays.asList(TestEntity.ATTR_oneRelatedValue), Direction.ASC).buildExecutor()
.getResultList()
.get(0).getId());
assertEquals((Long) 3L,
builder()
.setJoinType(Arrays.asList(TestEntity.ATTR_oneRelatedValue), JoinType.INNER)
.addSortBy(Arrays.asList(TestEntity.ATTR_oneRelatedValue), Direction.DESC).buildExecutor()
.getResultList().get(0).getId());
}
@Test
public void performsTwoFetches() {
JoinFetch<Customer> spec1 = new JoinFetch<Customer>(new String[] { "orders" }, JoinType.LEFT);
JoinFetch<Customer> spec2 = new JoinFetch<Customer>(new String[] { "orders2" }, JoinType.INNER);
Conjunction<Customer> spec = new Conjunction<Customer>(spec1, spec2);
List<Customer> customers = customerRepo.findAll(spec);
assertThat(customers).isNotEmpty();
for (Customer customer : customers) {
assertTrue(Hibernate.isInitialized(customer.getOrders()));
assertTrue(Hibernate.isInitialized(customer.getOrders2()));
}
}
@Override
public Page<TargetWithActionStatus> findAllTargetsOfRolloutGroupWithActionStatus(final Pageable pageRequest,
final long rolloutGroupId) {
throwExceptionIfRolloutGroupDoesNotExist(rolloutGroupId);
final CriteriaBuilder cb = entityManager.getCriteriaBuilder();
final CriteriaQuery<Object[]> query = cb.createQuery(Object[].class);
final CriteriaQuery<Long> countQuery = cb.createQuery(Long.class);
final Root<RolloutTargetGroup> targetRoot = query.distinct(true).from(RolloutTargetGroup.class);
final Join<RolloutTargetGroup, JpaTarget> targetJoin = targetRoot.join(RolloutTargetGroup_.target);
final ListJoin<RolloutTargetGroup, JpaAction> actionJoin = targetRoot.join(RolloutTargetGroup_.actions,
JoinType.LEFT);
final Root<RolloutTargetGroup> countQueryFrom = countQuery.distinct(true).from(RolloutTargetGroup.class);
countQueryFrom.join(RolloutTargetGroup_.target);
countQueryFrom.join(RolloutTargetGroup_.actions, JoinType.LEFT);
countQuery.select(cb.count(countQueryFrom)).where(cb
.equal(countQueryFrom.get(RolloutTargetGroup_.rolloutGroup).get(JpaRolloutGroup_.id), rolloutGroupId));
final Long totalCount = entityManager.createQuery(countQuery).getSingleResult();
final CriteriaQuery<Object[]> multiselect = query.multiselect(targetJoin, actionJoin.get(JpaAction_.status))
.where(cb.equal(targetRoot.get(RolloutTargetGroup_.rolloutGroup).get(JpaRolloutGroup_.id),
rolloutGroupId));
final List<TargetWithActionStatus> targetWithActionStatus = entityManager.createQuery(multiselect)
.setFirstResult((int) pageRequest.getOffset()).setMaxResults(pageRequest.getPageSize()).getResultList()
.stream().map(o -> new TargetWithActionStatus((Target) o[0], (Action.Status) o[1]))
.collect(Collectors.toList());
return new PageImpl<>(targetWithActionStatus, pageRequest, totalCount);
}
private List<SingularAttribute<?, ?>> getJoinAttributes(final JoinType inner) {
List<SingularAttribute<?, ?>> left = joinAttributes.get(inner);
if (left == null) {
left = new ArrayList<SingularAttribute<?, ?>>();
joinAttributes.put(inner, left);
}
return left;
}
/**
* @param installedTargetId
* the targetID which is installed to a distribution set to
* search for.
* @return the specification to search for a distribution set which is
* installed to the given targetId
*/
public static Specification<JpaDistributionSet> installedTarget(final String installedTargetId) {
return (dsRoot, query, cb) -> {
final ListJoin<JpaDistributionSet, JpaTarget> installedTargetJoin = dsRoot
.join(JpaDistributionSet_.installedAtTargets, JoinType.INNER);
return cb.equal(installedTargetJoin.get(JpaTarget_.controllerId), installedTargetId);
};
}
private String renderJoinType(JoinType joinType) {
switch ( joinType ) {
case INNER: {
return " inner join ";
}
case LEFT: {
return " left join ";
}
case RIGHT: {
return " right join ";
}
}
throw new IllegalStateException( "Unknown join type " + joinType );
}
/**
* Function to convert SinkCriteria to a {@link Specification}.
*/
private Specification<Sink> createSpecification(SinkCriteria criteria) {
Specification<Sink> specification = Specification.where(null);
if (criteria != null) {
if (criteria.getId() != null) {
specification = specification.and(buildSpecification(criteria.getId(), Sink_.id));
}
if (criteria.getName() != null) {
specification = specification.and(buildStringSpecification(criteria.getName(), Sink_.name));
}
if (criteria.getType() != null) {
specification = specification.and(buildSpecification(criteria.getType(), Sink_.type));
}
if (criteria.getRemark() != null) {
specification = specification.and(buildStringSpecification(criteria.getRemark(), Sink_.remark));
}
if (criteria.getCreatedBy() != null) {
specification = specification.and(buildStringSpecification(criteria.getCreatedBy(), Sink_.createdBy));
}
if (criteria.getCreatedDate() != null) {
specification = specification.and(buildRangeSpecification(criteria.getCreatedDate(), Sink_.createdDate));
}
if (criteria.getLastModifiedBy() != null) {
specification = specification.and(buildStringSpecification(criteria.getLastModifiedBy(), Sink_.lastModifiedBy));
}
if (criteria.getLastModifiedDate() != null) {
specification = specification.and(buildRangeSpecification(criteria.getLastModifiedDate(), Sink_.lastModifiedDate));
}
if (criteria.getBusinessId() != null) {
specification = specification.and(buildSpecification(criteria.getBusinessId(),
root -> root.join(Sink_.business, JoinType.LEFT).get(Business_.id)));
}
}
return specification;
}
/**
* {@link Specification} for retrieving {@link DistributionSet}s by tag.
*
* @param tagId
* the ID of the distribution set which must be assigned
* @return the {@link DistributionSet} {@link Specification}
*/
public static Specification<JpaDistributionSet> hasTag(final Long tagId) {
return (targetRoot, query, cb) -> {
final SetJoin<JpaDistributionSet, JpaDistributionSetTag> tags = targetRoot.join(JpaDistributionSet_.tags,
JoinType.LEFT);
return cb.equal(tags.get(JpaDistributionSetTag_.id), tagId);
};
}
/**
* Get the specification for the query which will find the commands which match the given criterion.
*
* @param root The {@link Root} (from) for the query
* @param cq The {@link CriteriaQuery} instance
* @param cb The {@link CriteriaBuilder} instance
* @param criterion The {@link Criterion} to match commands against
* @return A {@link Predicate} for this query
*/
public static Predicate findCommandsMatchingCriterion(
final Root<CommandEntity> root,
final CriteriaQuery<?> cq,
final CriteriaBuilder cb,
final Criterion criterion
) {
final Subquery<Long> criterionSubquery = cq.subquery(Long.class);
final Root<CommandEntity> criterionSubqueryRoot = criterionSubquery.from(CommandEntity.class);
criterionSubquery.select(criterionSubqueryRoot.get(CommandEntity_.id));
criterionSubquery.where(
cb.and(
PredicateUtils.createCriterionPredicate(
criterionSubqueryRoot,
criterionSubquery,
cb,
CommandEntity_.uniqueId,
CommandEntity_.name,
CommandEntity_.version,
CommandEntity_.status,
() -> criterionSubqueryRoot.join(CommandEntity_.tags, JoinType.INNER),
CommandEntity_.id,
criterion
),
cb.isNotEmpty(criterionSubqueryRoot.get(CommandEntity_.clusterCriteria))
)
);
return root.get(CommandEntity_.id).in(criterionSubquery);
}
@Test
public void testMapOrder() {
assertEquals(5, builder().setDefaultJoinType(JoinType.LEFT)
.addSortBy(Arrays.asList(TestEntity.ATTR_mapValue, "a"), Direction.DESC).buildExecutor().getResultList().size());
List<TestEntity> list = builder().addSortBy(Arrays.asList(TestEntity.ATTR_mapValue, "a"), Direction.ASC).buildExecutor()
.getResultList();
assertEquals((Long) 0L, list.get(1).getId());
list = builder().addSortBy(Arrays.asList(TestEntity.ATTR_mapValue, "a"), Direction.DESC).buildExecutor().getResultList();
assertEquals((Long) 3L, list.get(0).getId());
}
public static SingleParamSpecification<Branch> branchStatisticTranslated(final Boolean translated) {
return new SingleParamSpecification<Branch>(translated) {
@Override
public Predicate toPredicate(Root<Branch> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Join<Branch, BranchStatistic> branchStatisticJoin = root.join(Branch_.branchStatistic, JoinType.LEFT);
Predicate predicate = builder.equal(branchStatisticJoin.get(BranchStatistic_.forTranslationCount), 0L);
if (!translated) {
predicate = builder.not(predicate);
}
return predicate;
}
};
}
/**
* {@link Specification} for retrieving {@link Target}s that don't have the
* given distribution set in their action history
*
* @param distributionSetId
* the ID of the distribution set which must not be assigned
* @return the {@link Target} {@link Specification}
*/
public static Specification<JpaTarget> hasNotDistributionSetInActions(final Long distributionSetId) {
return (targetRoot, query, cb) -> {
final ListJoin<JpaTarget, JpaAction> actionsJoin = targetRoot.join(JpaTarget_.actions, JoinType.LEFT);
actionsJoin.on(cb.equal(actionsJoin.get(JpaAction_.distributionSet).get(JpaDistributionSet_.id),
distributionSetId));
return cb.isNull(actionsJoin.get(JpaAction_.id));
};
}
public JoinRelationshipTypeMapping() {
joinRelationshipTypes = new HashMap<>();
joinRelationshipTypes.put("one-to-many", JoinType.INNER);
joinRelationshipTypes.put("many-to-one", JoinType.INNER);
// joinRelationshipTypes.put("one-to-one", JoinType.INNER);
// joinRelationshipTypes.put("optional-one-to-one", JoinType.RIGHT);
// joinRelationshipTypes.put("one-to-optional-one", JoinType.LEFT);
// joinRelationshipTypes.put("optional-many-to-one", JoinType.RIGHT);
joinRelationshipTypes.put("many-to-optional-one", JoinType.RIGHT);
joinRelationshipTypes.put("optional-one-to-many", JoinType.LEFT);
// joinRelationshipTypes.put("one-to-optional-many", JoinType.LEFT);
}
public void testMethod_joinContainerWithRegularAndFetchJoins(
@Joins(value = {
@Join(path = "join1", alias = "alias1", type = JoinType.INNER, distinct = true),
@Join(path = "join2", alias = "alias2", type = JoinType.LEFT, distinct = false)
}, fetch = {
@JoinFetch(paths = { "fetch1" }),
@JoinFetch(paths = { "fetch2" }, joinType = JoinType.INNER)
})
@Spec(path = "path1", spec = Like.class) Specification<Object> spec) {
}
@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();
}
public AbstractJoinImpl(
CriteriaBuilderImpl criteriaBuilder,
PathSource<Z> pathSource,
Attribute<? super Z, X> joinAttribute,
JoinType joinType) {
this( criteriaBuilder, joinAttribute.getJavaType(), pathSource, joinAttribute, joinType );
}
@Override
public Predicate getPredicate(Root<CodeComment> root, CriteriaBuilder builder) {
Join<?, ?> join = root.join(CodeComment.PROP_REPLIES, JoinType.LEFT);
Path<String> attribute = join.get(CodeCommentReply.PROP_CONTENT);
join.on(builder.like(builder.lower(attribute), "%" + value.toLowerCase().replace('*', '%') + "%"));
return join.isNotNull();
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
Join<?, ?> join = root.join(PullRequest.PROP_REVIEWS, JoinType.LEFT);
Path<?> userPath = EntityQuery.getPath(join, PullRequestReview.PROP_USER);
Path<?> approvedPath = EntityQuery.getPath(join, PullRequestReview.PROP_RESULT + "." + ReviewResult.PROP_APPROVED);
join.on(builder.and(
builder.equal(userPath, user),
builder.equal(approvedPath, false)));
return join.isNotNull();
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
Join<?, ?> join = root.join(PullRequest.PROP_REVIEWS, JoinType.LEFT);
Path<?> userPath = EntityQuery.getPath(join, PullRequestReview.PROP_USER);
Path<?> approvedPath = EntityQuery.getPath(join, PullRequestReview.PROP_RESULT + "." + ReviewResult.PROP_APPROVED);
join.on(builder.and(
builder.isNotNull(userPath),
builder.isNull(approvedPath)));
return join.isNotNull();
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
Join<?, ?> join = root.join(PullRequest.PROP_REVIEWS, JoinType.LEFT);
Path<?> userPath = EntityQuery.getPath(join, PullRequestReview.PROP_USER);
Path<?> approvedPath = EntityQuery.getPath(join, PullRequestReview.PROP_RESULT + "." + ReviewResult.PROP_APPROVED);
join.on(builder.and(
builder.isNotNull(userPath),
builder.equal(approvedPath, false)));
return join.isNotNull();
}
@Override
@SuppressWarnings({"unchecked"})
public <X, Y> CollectionJoin<X, Y> joinCollection(String attributeName, JoinType jt) {
final Attribute<X, ?> attribute = (Attribute<X, ?>) locateAttribute( attributeName );
if ( !attribute.isCollection() ) {
throw new IllegalArgumentException( "Requested attribute was not a collection" );
}
final PluralAttribute pluralAttribute = (PluralAttribute) attribute;
if ( !PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) {
throw new IllegalArgumentException( "Requested attribute was not a collection" );
}
return (CollectionJoin<X, Y>) join( (CollectionAttribute) attribute, jt );
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
Join<?, ?> join = root.join(PullRequest.PROP_REVIEWS, JoinType.LEFT);
Path<?> userPath = EntityQuery.getPath(join, PullRequestReview.PROP_USER);
Path<?> approvedPath = EntityQuery.getPath(join, PullRequestReview.PROP_RESULT + "." + ReviewResult.PROP_APPROVED);
join.on(builder.and(
builder.equal(userPath, user),
builder.isNull(approvedPath)));
return join.isNotNull();
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
if (User.get() != null) {
Join<?, ?> join = root.join(PullRequest.PROP_ASSIGNMENTS, JoinType.LEFT);
Path<?> userPath = EntityQuery.getPath(join, PullRequestAssignment.PROP_USER);
join.on(builder.equal(userPath, User.get()));
return join.isNotNull();
} else {
throw new OneException("Please login to perform this query");
}
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
Join<?, ?> join = root.join(PullRequest.PROP_REVIEWS, JoinType.LEFT);
Path<?> userPath = EntityQuery.getPath(join, PullRequestReview.PROP_USER);
Path<?> approvedPath = EntityQuery.getPath(join, PullRequestReview.PROP_RESULT + "." + ReviewResult.PROP_APPROVED);
join.on(builder.and(
builder.equal(userPath, user),
builder.equal(approvedPath, true)));
return join.isNotNull();
}
@Override
public Predicate getPredicate(Root<PullRequest> root, CriteriaBuilder builder) {
Join<?, ?> join = root.join(PullRequest.PROP_ASSIGNMENTS, JoinType.LEFT);
Path<?> userPath = EntityQuery.getPath(join, PullRequestAssignment.PROP_USER);
join.on(builder.equal(userPath, user));
return join.isNotNull();
}