use of com.blazebit.persistence.PaginatedCriteriaBuilder in project blaze-persistence by Blazebit.
the class AbstractEntityViewAwareRepository method getQuery.
protected <S extends E> TypedQuery<V> getQuery(Specification<S> spec, Class<S> domainClass, Pageable pageable, Sort sort) {
BlazeCriteriaQuery<S> cq = BlazeCriteria.get(cbf, domainClass);
Root<S> root = this.applySpecificationToCriteria(spec, domainClass, cq);
Class<V> entityViewClass = metadata == null || metadata.getEntityViewClass() == null ? this.entityViewClass : (Class<V>) metadata.getEntityViewClass();
if (sort != null && entityViewClass == null) {
cq.orderBy(QueryUtils.toOrders(sort, root, BlazeCriteria.get(cbf)));
}
CriteriaBuilder<S> cb = cq.createCriteriaBuilder(entityManager);
String[] fetches = EMPTY;
if (metadata != null && metadata.getEntityGraph() != null && (fetches = metadata.getEntityGraph().attributePaths()).length != 0) {
cb.fetch(fetches);
}
boolean withCountQuery = true;
boolean withKeysetExtraction = false;
boolean withExtractAllKeysets = false;
TypedQuery<V> query;
if (entityViewClass == null) {
if (pageable == null) {
query = (TypedQuery<V>) cb.getQuery();
} else {
PaginatedCriteriaBuilder<S> paginatedCriteriaBuilder;
if (pageable instanceof KeysetPageable) {
KeysetPageable keysetPageable = (KeysetPageable) pageable;
paginatedCriteriaBuilder = cb.page(keysetPageable.getKeysetPage(), getOffset(pageable), pageable.getPageSize());
withCountQuery = keysetPageable.isWithCountQuery();
withKeysetExtraction = true;
withExtractAllKeysets = keysetPageable.isWithExtractAllKeysets();
} else {
paginatedCriteriaBuilder = cb.page(getOffset(pageable), pageable.getPageSize());
}
if (withKeysetExtraction) {
paginatedCriteriaBuilder.withKeysetExtraction(true);
paginatedCriteriaBuilder.withExtractAllKeysets(withExtractAllKeysets);
}
paginatedCriteriaBuilder.withCountQuery(withCountQuery);
query = (TypedQuery<V>) paginatedCriteriaBuilder.getQuery();
}
} else {
if (pageable == null) {
EntityViewSetting<V, CriteriaBuilder<V>> setting = EntityViewSetting.create(entityViewClass);
CriteriaBuilder<V> fqb = evm.applySetting(setting, cb);
if (sort != null) {
EntityViewSortUtil.applySort(evm, entityViewClass, fqb, sort);
}
query = fqb.getQuery();
} else {
EntityViewSetting<V, PaginatedCriteriaBuilder<V>> setting = EntityViewSetting.create(entityViewClass, getOffset(pageable), pageable.getPageSize());
if (pageable instanceof KeysetPageable) {
KeysetPageable keysetPageable = (KeysetPageable) pageable;
setting.withKeysetPage(keysetPageable.getKeysetPage());
withCountQuery = keysetPageable.isWithCountQuery();
withKeysetExtraction = true;
withExtractAllKeysets = keysetPageable.isWithExtractAllKeysets();
}
PaginatedCriteriaBuilder<V> paginatedCriteriaBuilder = evm.applySetting(setting, cb);
if (withKeysetExtraction) {
paginatedCriteriaBuilder.withKeysetExtraction(true);
paginatedCriteriaBuilder.withExtractAllKeysets(withExtractAllKeysets);
}
paginatedCriteriaBuilder.withCountQuery(withCountQuery);
if (sort != null || (sort = pageable.getSort()) != null) {
EntityViewSortUtil.applySort(evm, entityViewClass, paginatedCriteriaBuilder, sort);
}
query = paginatedCriteriaBuilder.getQuery();
}
}
return this.applyRepositoryMethodMetadata(query, fetches.length == 0);
}
use of com.blazebit.persistence.PaginatedCriteriaBuilder in project blaze-persistence by Blazebit.
the class CTEShowcase method run.
@Override
public void run() {
testDataGenerator.generateTestData();
EntityViewSetting<BasicCatView, CriteriaBuilder<BasicCatView>> basicCatSetting = EntityViewSetting.create(BasicCatView.class);
BasicCatView someCat = catDataAccess.getCatByName("G - Generation 2 - Cat 2/1", basicCatSetting);
// entity-view example with CTE
System.out.println(heading("Family tree of " + someCat));
print(catDataAccess.getCatHierarchy(someCat.getId(), basicCatSetting));
// pagination & entity views
EntityViewSetting<BasicCatView, PaginatedCriteriaBuilder<BasicCatView>> paginationSetting = EntityViewSetting.create(BasicCatView.class, 0, 3);
PagedList<BasicCatView> pagedResults = catDataAccess.getPaginatedCats(paginationSetting);
System.out.println(heading("Page 1"));
print(pagedResults);
// insert new cat
// in the sort order defined by CatDataAccess#getPaginatedCats, this cat is inserted at index 1 (0-based)
testDataGenerator.addCat("B - New cat");
// since we use keyset pagination, the inserted cat does not influence the next page
// depending on the firstRow parameter and the passed keyset page, the criteria builder will automatically decide
// if it can use keyset pagination or if it must perform offset pagination
paginationSetting = EntityViewSetting.create(BasicCatView.class, 3, 3);
paginationSetting.withKeysetPage(pagedResults.getKeysetPage());
pagedResults = catDataAccess.getPaginatedCats(paginationSetting);
System.out.println(heading("Page 2"));
print(pagedResults);
// scroll back to page 1
// page 1 will now contain the new cat
paginationSetting = EntityViewSetting.create(BasicCatView.class, 0, 3);
paginationSetting.withKeysetPage(pagedResults.getKeysetPage());
pagedResults = catDataAccess.getPaginatedCats(paginationSetting);
System.out.println(heading("Back at Page 1"));
print(pagedResults);
}
use of com.blazebit.persistence.PaginatedCriteriaBuilder in project blaze-persistence by Blazebit.
the class SubviewEntityViewSettingTest method testEntityViewSettingFilterFilteredSubview.
@Test
@Category({ NoEclipselink.class })
public // Eclipselink does not support VALUE() dereferencing
void testEntityViewSettingFilterFilteredSubview() {
EntityViewManager evm = build(DocumentMasterView.class, SimpleDocumentView.class, PersonSubView.class, PersonSubViewFiltered.class);
// Base setting
EntityViewSetting<DocumentMasterView, PaginatedCriteriaBuilder<DocumentMasterView>> setting = EntityViewSetting.create(DocumentMasterView.class, 0, 1);
// Query
CriteriaBuilder<Document> cb = cbf.create(em, Document.class);
setting.addAttributeFilter("myContactPerson.name", "Owner");
setting.addAttributeSorter("myContactPerson.name", Sorters.descending());
setting.addAttributeSorter("id", Sorters.descending());
setting.addOptionalParameter("contactPersonNumber", 1);
PaginatedCriteriaBuilder<DocumentMasterView> paginatedCb = evm.applySetting(setting, cb);
PagedList<DocumentMasterView> result = paginatedCb.getResultList();
assertEquals(1, result.size());
assertEquals(2, result.getTotalSize());
assertEquals("HisTest", result.get(0).getName());
assertEquals("DocumentOwnerSlave".toUpperCase(), result.get(0).getOwner().getName());
}
use of com.blazebit.persistence.PaginatedCriteriaBuilder in project blaze-persistence by Blazebit.
the class MappingSubqueryTest method testSubqueryWithExpression.
@Test
@Category(NoDB2.class)
public void testSubqueryWithExpression() {
EntityViewManager evm = build(DocumentWithExpressionSubqueryView.class);
// Base setting
EntityViewSetting<DocumentWithExpressionSubqueryView, PaginatedCriteriaBuilder<DocumentWithExpressionSubqueryView>> setting = EntityViewSetting.create(DocumentWithExpressionSubqueryView.class, 0, 2);
// Query
CriteriaBuilder<Document> cb = cbf.create(em, Document.class);
setting.addAttributeSorter("contactCount", Sorters.descending());
setting.addAttributeSorter("id", Sorters.descending());
PaginatedCriteriaBuilder<DocumentWithExpressionSubqueryView> paginatedCb = evm.applySetting(setting, cb);
// TODO: Since case when statements in order bys use the resolved expression and because hibernate does not resolve
// the select alias in nested expressions, we can't run this on DB2
// The fix is to use the select alias
PagedList<DocumentWithExpressionSubqueryView> result = paginatedCb.getResultList();
assertEquals(2, result.size());
assertEquals(2, result.getTotalSize());
assertEquals(doc2.getName(), result.get(0).getName());
assertEquals(Long.valueOf(22), result.get(0).getContactCount());
assertEquals(doc1.getName(), result.get(1).getName());
assertEquals(Long.valueOf(11), result.get(1).getContactCount());
}
use of com.blazebit.persistence.PaginatedCriteriaBuilder in project blaze-persistence by Blazebit.
the class AbstractCorrelatedSubselectTupleTransformer method prepare.
private void prepare() {
JpaProvider jpaProvider = entityViewConfiguration.getCriteriaBuilder().getService(JpaProvider.class);
FullQueryBuilder<?, ?> queryBuilder = entityViewConfiguration.getCriteriaBuilder();
Map<String, Object> optionalParameters = entityViewConfiguration.getOptionalParameters();
Class<?> correlationBasisEntityType = correlationBasisEntity;
String viewRootExpression = viewRootAlias;
EmbeddingViewJpqlMacro embeddingViewJpqlMacro = entityViewConfiguration.getEmbeddingViewJpqlMacro();
ViewJpqlMacro viewJpqlMacro = entityViewConfiguration.getViewJpqlMacro();
if (queryBuilder instanceof PaginatedCriteriaBuilder<?>) {
criteriaBuilder = queryBuilder.copyCriteriaBuilder(Object[].class, false);
} else {
LimitBuilder<?> limitBuilder = (LimitBuilder<?>) queryBuilder;
// To set the limit, we need the JPA provider to support this
if (jpaProvider.supportsSubqueryInFunction() && (limitBuilder.getFirstResult() > 0 || limitBuilder.getMaxResults() < Integer.MAX_VALUE)) {
// we must turn this query builder into a paginated criteria builder first
try {
criteriaBuilder = queryBuilder.copyCriteriaBuilder(Object[].class, true).page(limitBuilder.getFirstResult(), limitBuilder.getMaxResults()).copyCriteriaBuilder(Object[].class, false);
} catch (IllegalStateException ex) {
LOG.log(Level.WARNING, "Could not create a paginated criteria builder for SUBSELECT fetching which might lead to bad performance", ex);
criteriaBuilder = queryBuilder.copyCriteriaBuilder(Object[].class, false);
}
} else {
// Regular query without limit/offset
criteriaBuilder = queryBuilder.copyCriteriaBuilder(Object[].class, false);
}
}
int originalFirstResult = 0;
int originalMaxResults = Integer.MAX_VALUE;
// A copied query that is extended with further joins can't possibly use the limits provided by the outer query
((LimitBuilder<?>) criteriaBuilder).setFirstResult(originalFirstResult);
((LimitBuilder<?>) criteriaBuilder).setMaxResults(originalMaxResults);
this.viewRootJpqlMacro = new CorrelatedSubqueryViewRootJpqlMacro(criteriaBuilder, optionalParameters, false, viewRootEntityClass, idAttributePath, viewRootExpression);
criteriaBuilder.registerMacro("view", viewJpqlMacro);
criteriaBuilder.registerMacro("view_root", viewRootJpqlMacro);
criteriaBuilder.registerMacro("embedding_view", embeddingViewJpqlMacro);
String oldViewPath = viewJpqlMacro.getViewPath();
String oldEmbeddingViewPath = embeddingViewJpqlMacro.getEmbeddingViewPath();
viewJpqlMacro.setViewPath(correlationResultExpression);
embeddingViewJpqlMacro.setEmbeddingViewPath(embeddingViewPath);
String joinBase = embeddingViewPath;
SubqueryCorrelationBuilder correlationBuilder = new SubqueryCorrelationBuilder(queryBuilder, optionalParameters, criteriaBuilder, correlationAlias, correlationExternalAlias, correlationResultExpression, correlationBasisType, correlationBasisEntityType, joinBase, attributePath, 1, limiter, true);
CorrelationProvider provider = correlationProviderFactory.create(entityViewConfiguration.getCriteriaBuilder(), entityViewConfiguration.getOptionalParameters());
provider.applyCorrelation(correlationBuilder, correlationBasisExpression);
if (criteriaBuilder instanceof LimitBuilder<?>) {
if (originalFirstResult != ((LimitBuilder<?>) criteriaBuilder).getFirstResult() || originalMaxResults != ((LimitBuilder<?>) criteriaBuilder).getMaxResults()) {
throw new IllegalArgumentException("Correlation provider '" + provider + "' wrongly uses setFirstResult() or setMaxResults() on the query builder which might lead to wrong results. Use SELECT fetching with batch size 1 or reformulate the correlation provider to use the limit/offset in a subquery!");
}
}
if (fetches.length != 0) {
for (int i = 0; i < fetches.length; i++) {
criteriaBuilder.fetch(fetches[i]);
}
}
if (indexFetches.length != 0) {
for (int i = 0; i < indexFetches.length; i++) {
criteriaBuilder.fetch(indexFetches[i]);
}
}
// Before we can determine whether we use view roots or embedding views, we need to add all selects, otherwise macros might report false although they are used
final String correlationRoot = correlationBuilder.getCorrelationRoot();
final int tupleSuffix = maximumViewMapperCount + 1 + (indexCorrelator == null && indexExpression == null ? 0 : 1);
ObjectBuilder<Object[]> objectBuilder = (ObjectBuilder<Object[]>) correlator.finish(criteriaBuilder, entityViewConfiguration, 0, tupleSuffix, correlationRoot, embeddingViewJpqlMacro, true);
final boolean usesViewRoot = viewRootJpqlMacro.usesViewMacro();
final boolean usesEmbeddingView = embeddingViewJpqlMacro.usesEmbeddingView();
if (usesEmbeddingView && !(embeddingViewType instanceof ViewType<?>)) {
throw new IllegalStateException("The use of EMBEDDING_VIEW in the correlation for '" + embeddingViewType.getJavaType().getName() + "." + attributePath.substring(attributePath.lastIndexOf('.') + 1) + "' is illegal because the embedding view type '" + embeddingViewType.getJavaType().getName() + "' does not declare a @IdMapping!");
} else if (usesViewRoot && !(viewRootType instanceof ViewType<?>)) {
throw new IllegalStateException("The use of VIEW_ROOT in the correlation for '" + embeddingViewType.getJavaType().getName() + "." + attributePath.substring(attributePath.lastIndexOf('.') + 1) + "' is illegal because the view root type '" + viewRootType.getJavaType().getName() + "' does not declare a @IdMapping!");
}
final int maximumSlotsFilled;
final int elementKeyIndex;
final int elementViewIndex;
if (usesEmbeddingView) {
maximumSlotsFilled = embeddingViewIdMapperCount == 0 ? 1 : embeddingViewIdMapperCount;
elementKeyIndex = (maximumViewMapperCount - maximumSlotsFilled) + 2 + valueIndex;
elementViewIndex = (maximumViewMapperCount - maximumSlotsFilled) + 1 + valueIndex;
viewIndex = embeddingViewIndex;
} else if (usesViewRoot) {
maximumSlotsFilled = viewRootIdMapperCount == 0 ? 1 : viewRootIdMapperCount;
elementKeyIndex = (maximumViewMapperCount - maximumSlotsFilled) + 2 + valueIndex;
elementViewIndex = (maximumViewMapperCount - maximumSlotsFilled) + 1 + valueIndex;
viewIndex = viewRootIndex;
} else {
maximumSlotsFilled = 0;
elementKeyIndex = maximumViewMapperCount + 1 + valueIndex;
elementViewIndex = 1 + valueIndex;
viewIndex = -1;
}
for (int i = maximumSlotsFilled; i < maximumViewMapperCount; i++) {
criteriaBuilder.select("NULL");
}
ExpressionFactory ef = criteriaBuilder.getService(ExpressionFactory.class);
if (usesEmbeddingView) {
EntityViewConfiguration configuration = new EntityViewConfiguration(criteriaBuilder, ef, new MutableViewJpqlMacro(), new MutableEmbeddingViewJpqlMacro(), Collections.<String, Object>emptyMap(), Collections.<String, Object>emptyMap(), entityViewConfiguration.getFetches(), attributePath);
ObjectBuilder<Object[]> embeddingViewObjectBuilder = createViewAwareObjectBuilder(criteriaBuilder, embeddingViewType, configuration, embeddingViewIdExpression);
if (embeddingViewObjectBuilder == null) {
criteriaBuilder.select(embeddingViewIdExpression);
} else {
criteriaBuilder.selectNew(objectBuilder = new LateAdditionalObjectBuilder(objectBuilder, embeddingViewObjectBuilder, true));
}
} else if (usesViewRoot) {
EntityViewConfiguration configuration = new EntityViewConfiguration(criteriaBuilder, ef, new MutableViewJpqlMacro(), new MutableEmbeddingViewJpqlMacro(), Collections.<String, Object>emptyMap(), Collections.<String, Object>emptyMap(), entityViewConfiguration.getFetches(), attributePath);
ObjectBuilder<Object[]> viewRootObjectBuilder = createViewAwareObjectBuilder(criteriaBuilder, viewRootType, configuration, viewRootIdExpression);
if (viewRootObjectBuilder == null) {
criteriaBuilder.select(viewRootIdExpression);
} else {
criteriaBuilder.selectNew(objectBuilder = new LateAdditionalObjectBuilder(objectBuilder, viewRootObjectBuilder, true));
}
}
criteriaBuilder.select(correlationKeyExpression);
if (indexCorrelator != null) {
ObjectBuilder<?> indexBuilder = indexCorrelator.finish(criteriaBuilder, entityViewConfiguration, maximumViewMapperCount + 2, 0, indexExpression, embeddingViewJpqlMacro, true);
if (indexBuilder != null) {
criteriaBuilder.selectNew(new LateAdditionalObjectBuilder(objectBuilder, indexBuilder, false));
}
}
populateParameters(entityViewConfiguration, criteriaBuilder);
viewJpqlMacro.setViewPath(oldViewPath);
embeddingViewJpqlMacro.setEmbeddingViewPath(oldEmbeddingViewPath);
List<Object[]> resultList = (List<Object[]>) criteriaBuilder.getResultList();
Map<Object, Map<Object, Object>> collections = new HashMap<>(resultList.size());
for (int i = 0; i < resultList.size(); i++) {
Object[] element = resultList.get(i);
Map<Object, Object> viewRootResult = collections.get(element[elementViewIndex]);
if (viewRootResult == null) {
viewRootResult = new HashMap<>();
collections.put(element[elementViewIndex], viewRootResult);
}
if (this.containerAccumulator == null) {
viewRootResult.put(element[elementKeyIndex], element[valueIndex]);
} else {
Object result = viewRootResult.get(element[elementKeyIndex]);
if (result == null) {
result = createDefaultResult();
viewRootResult.put(element[elementKeyIndex], result);
}
Object indexObject = null;
if (indexCorrelator != null || indexExpression != null) {
indexObject = element[elementKeyIndex + 1];
}
this.containerAccumulator.add(result, indexObject, element[valueIndex], isRecording());
}
}
this.collections = collections;
}
Aggregations