org.bitbucket.brunneng.qb.SpringQueryBuilderUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of query-builder Show documentation
Show all versions of query-builder Show documentation
Compact tool for building SQL, JPA or hibernate queries.
Supports utilities for spring pagination and sorting.
Supports extending to other types of query languages.
Has no transitive dependencies - use only what you need.
The newest version!
package org.bitbucket.brunneng.qb;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import javax.persistence.Query;
import java.util.Iterator;
import java.util.List;
/**
* The utility class which holds static methods for integration of query builders with spring data.
*/
public final class SpringQueryBuilderUtils {
private SpringQueryBuilderUtils() {
}
/**
* Loads the page of objects of the class entityClass using query and parameters from given
* jpqlQueryBuilder and page description with
* optional sorting from given pageable
* @param jpqlQueryBuilder jpql query builder, which will be used to get request to load the page
* @param pageable description of the required page with optional sorting.
* @param uniqueFieldForSort unique field to apply sorting to make stable results across different
* paging request. Can be null, but it's highly recommended to specify it.
* @param type of elements of the page
* @return loaded page
*/
public static Page loadPage(AbstractJpqlQueryBuilder jpqlQueryBuilder, Pageable pageable,
String uniqueFieldForSort) {
Long totalCount = jpqlQueryBuilder.buildCountQuery().getSingleResult();
Sort sort = pageable.getSort();
if (uniqueFieldForSort != null && sort.getOrderFor(uniqueFieldForSort) == null) {
sort = sort.and(Sort.by(uniqueFieldForSort));
}
applySort(jpqlQueryBuilder, sort);
Query query = jpqlQueryBuilder.build();
if (pageable.isPaged()) {
query.setFirstResult((int) pageable.getOffset());
query.setMaxResults(pageable.getPageSize());
}
List res = query.getResultList();
return new PageImpl<>(res, pageable, totalCount);
}
/**
* Applies sorting from the given sort to the given jpqlQueryBuilder.
* Does nothing if sort is null or empty.
* @param jpqlQueryBuilder the query builder to apply sort to it
* @param sort configuration of sorting.
*/
public static void applySort(AbstractJpqlQueryBuilder jpqlQueryBuilder, Sort sort) {
if (sort == null) {
return;
}
Iterator sortIterator = sort.iterator();
if (!sortIterator.hasNext()) {
return;
}
jpqlQueryBuilder.append(" order by");
String targetAlias = jpqlQueryBuilder.findTargetAlias();
while (sortIterator.hasNext()) {
Sort.Order order = sortIterator.next();
jpqlQueryBuilder.append(String.format(" %s.%s %s", targetAlias, order.getProperty(), order.getDirection()));
if (sortIterator.hasNext()) {
jpqlQueryBuilder.append(",");
}
}
}
}