package eu.eudat.queryable.hibernatequeryablelist; import eu.eudat.entities.DataEntity; import eu.eudat.queryable.QueryableList; import eu.eudat.queryable.exceptions.NotSingleResultException; import eu.eudat.queryable.predicates.NestedQuerySinglePredicate; import eu.eudat.queryable.predicates.OrderByPredicate; import eu.eudat.queryable.predicates.SelectPredicate; import eu.eudat.queryable.predicates.SinglePredicate; import eu.eudat.queryable.types.FieldSelectionType; import eu.eudat.queryable.types.SelectionField; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import javax.persistence.criteria.*; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; public class QueryableHibernateList implements QueryableList { private EntityManager manager; private CriteriaQuery query; private Class tClass; private Root root; private Root nestedQueryRoot; private Subquery subquery; private List> singlePredicates = new LinkedList<>(); private List> nestedPredicates = new LinkedList<>(); private List> orderings = new LinkedList<>(); private List fields = new LinkedList<>(); private Integer length; private Integer offset; private Set hints; private String hint; public QueryableHibernateList(EntityManager manager, Class tClass) { this.manager = manager; this.tClass = tClass; } public QueryableHibernateList setManager(EntityManager manager) { this.manager = manager; return this; } public QueryableList withHint(String hint) { this.hint = hint; return this; } public QueryableList setHints(Set hints) { this.hints = hints; return this; } @Override public QueryableList withFields(List fields) { this.fields = fields; return this; } private QueryableList selectFields() { List rootFields = fields.stream().map(field -> root.get(field)).collect(Collectors.toList()); this.query.select(this.manager.getCriteriaBuilder().construct(tClass, rootFields.toArray(new Selection[rootFields.size()]))); return this; } public QueryableHibernateList setEntity(Class type) { CriteriaBuilder builder = this.manager.getCriteriaBuilder(); this.query = builder.createQuery(type); this.root = this.query.from(this.tClass); return this; } public void initiateQueryableList(Class type) { CriteriaBuilder builder = this.manager.getCriteriaBuilder(); this.query = builder.createQuery(type); } @Override public QueryableList skip(Integer offset) { this.offset = offset; return this; } @Override public QueryableList take(Integer length) { this.length = length; return this; } public QueryableList where(SinglePredicate predicate) { this.singlePredicates.add(predicate); return this; } public QueryableList where(NestedQuerySinglePredicate predicate) { this.nestedPredicates.add(predicate); return this; } public List select(SelectPredicate predicate) { return this.toList().stream().map(item -> predicate.applySelection(item)).collect(Collectors.toList()); } public CompletableFuture> selectAsync(SelectPredicate predicate) { return this.toListAsync().thenApplyAsync(items -> items.stream().map(item -> predicate.applySelection(item)).collect(Collectors.toList())); } public QueryableList distinct() { this.query.distinct(true); return this; } public QueryableList orderBy(OrderByPredicate predicate) { this.orderings.add(predicate); return this; } public Long count() { CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); Root root = criteriaQuery.from(tClass); criteriaQuery.select(criteriaBuilder.count(root)); criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, root, this.nestedPredicates, this.nestedQueryRoot)); return this.manager.createQuery(criteriaQuery).getSingleResult(); } public CompletableFuture countAsync() { CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Long.class); Root root = criteriaQuery.from(tClass); criteriaQuery.select(criteriaBuilder.count(root)); criteriaQuery.where(this.generateWherePredicates(this.singlePredicates, root, this.nestedPredicates, this.nestedQueryRoot)); return CompletableFuture.supplyAsync(() -> this.manager.createQuery(criteriaQuery).getSingleResult()); } private Predicate[] generateWherePredicates(List> singlePredicates, Root root, List> nestedPredicates, Root nestedQueryRoot) { List predicates = new LinkedList<>(); predicates.addAll(Arrays.asList(this.generateSingleWherePredicates(singlePredicates, root))); predicates.addAll(Arrays.asList(this.generateNestedWherePredicates(nestedPredicates, root, nestedQueryRoot))); return predicates.toArray(new Predicate[predicates.size()]); } private Predicate[] generateSingleWherePredicates(List> singlePredicates, Root root) { List predicates = new LinkedList<>(); for (SinglePredicate singlePredicate : singlePredicates) { predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); } return predicates.toArray(new Predicate[predicates.size()]); } private Predicate[] generateNestedWherePredicates(List> nestedPredicates, Root root, Root nestedQueryRoot) { List predicates = new LinkedList<>(); for (NestedQuerySinglePredicate singlePredicate : nestedPredicates) { predicates.add(singlePredicate.applyPredicate(this.manager.getCriteriaBuilder(), root, nestedQueryRoot)); } return predicates.toArray(new Predicate[predicates.size()]); } private Order[] generateOrderPredicates(List> orderByPredicates, Root root) { List predicates = new LinkedList<>(); for (OrderByPredicate orderPredicate : orderByPredicates) { predicates.add(orderPredicate.applyPredicate(this.manager.getCriteriaBuilder(), root)); } return predicates.toArray(new Order[predicates.size()]); } public List toList() { this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); if (this.fields != null && !this.fields.isEmpty()) this.selectFields(); TypedQuery typedQuery = this.manager.createQuery(this.query); if (this.offset != null) typedQuery.setFirstResult(this.offset); if (this.length != null) typedQuery.setMaxResults(this.length); if (this.hint != null && this.hints.contains(hint)) { List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); if (ids != null && !ids.isEmpty()) typedQuery = queryWithHint(ids); } return typedQuery.getResultList(); } public CompletableFuture> toListAsync() { this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); if (!this.orderings.isEmpty()) this.query.orderBy(this.generateOrderPredicates(this.orderings, this.root)); if (this.fields != null && !this.fields.isEmpty()) this.selectFields(); TypedQuery typedQuery = this.manager.createQuery(this.query); if (this.offset != null) typedQuery.setFirstResult(this.offset); if (this.length != null) typedQuery.setMaxResults(this.length); return CompletableFuture.supplyAsync(() -> { if (this.hint != null && this.hints.contains(hint)) { List ids = typedQuery.getResultList().stream().map(item -> item.getKeys()).collect(Collectors.toList()); if (ids != null && !ids.isEmpty()) return queryWithHint(ids).getResultList(); } return typedQuery.getResultList(); }); } public T getSingle() { this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); if (this.fields != null && !this.fields.isEmpty()) this.selectFields(); TypedQuery typedQuery = this.manager.createQuery(this.query); if (this.hint != null) typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); return typedQuery.getSingleResult(); } public CompletableFuture getSingleAsync() { this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); if (this.fields != null && !this.fields.isEmpty()) this.selectFields(); TypedQuery typedQuery = this.manager.createQuery(this.query); if (this.hint != null) typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); return CompletableFuture.supplyAsync(() -> typedQuery.getSingleResult()); } public T getSingleOrDefault() { this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); if (this.fields != null && !this.fields.isEmpty()) this.selectFields(); TypedQuery typedQuery = this.manager.createQuery(this.query); if (this.hint != null) typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); List results = typedQuery.getResultList(); if (results.size() == 0) return null; if (results.size() == 1) return results.get(0); else throw new NotSingleResultException("Query returned more than one items"); } public CompletableFuture getSingleOrDefaultAsync() { this.query.where(this.generateWherePredicates(this.singlePredicates, this.root, this.nestedPredicates, this.nestedQueryRoot)); if (this.fields != null && !this.fields.isEmpty()) this.selectFields(); TypedQuery typedQuery = this.manager.createQuery(this.query); if (this.hint != null) typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); return CompletableFuture.supplyAsync(() -> typedQuery.getResultList()).thenApply(list -> { if (list.size() == 0) return null; if (list.size() == 1) return list.get(0); else throw new NotSingleResultException("Query returned more than one items"); }); } private TypedQuery queryWithHint(List ids) { CriteriaBuilder criteriaBuilder = this.manager.getCriteriaBuilder(); CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(tClass); Root criteriaRoot = criteriaQuery.from(this.tClass); criteriaQuery.where(criteriaRoot.get("id").in(ids)); if (!this.orderings.isEmpty()) criteriaQuery.orderBy(this.generateOrderPredicates(this.orderings, criteriaRoot)); TypedQuery typedQuery = this.manager.createQuery(criteriaQuery); typedQuery.setHint("javax.persistence.fetchgraph", this.manager.getEntityGraph(this.hint)); return typedQuery; } @Override public Subquery subQuery(SinglePredicate predicate, List fields) { Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); this.nestedQueryRoot = subquery.from(this.tClass); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); return subquery; } @Override public Subquery subQuery(NestedQuerySinglePredicate predicate, List fields) { Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(this.tClass); this.nestedQueryRoot = subquery.from(this.tClass); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); subquery.select(this.nestedQueryRoot.get(fields.get(0).getField())); return subquery; } @Override public Subquery subQueryCount(SinglePredicate predicate, List fields) { Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); this.nestedQueryRoot = subquery.from(this.tClass); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); return subquery; } @Override public Subquery subQueryCount(NestedQuerySinglePredicate predicate, List fields) { Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(Long.class); this.nestedQueryRoot = subquery.from(this.tClass); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); subquery.select(this.manager.getCriteriaBuilder().count(this.nestedQueryRoot.get(fields.get(0).getField()))); return subquery; } @Override public Subquery subQueryMax(SinglePredicate predicate, List fields, Class uClass) { Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); this.nestedQueryRoot = subquery.from(this.tClass); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.nestedQueryRoot)); if (fields.get(0).getType() == FieldSelectionType.FIELD) subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); } return subquery; } @Override public Subquery subQueryMax(NestedQuerySinglePredicate predicate, List fields, Class uClass) { Subquery subquery = this.manager.getCriteriaBuilder().createQuery().subquery(uClass); this.nestedQueryRoot = subquery.from(this.tClass); subquery.where(predicate.applyPredicate(this.manager.getCriteriaBuilder(), this.root, this.nestedQueryRoot)); if (fields.get(0).getType() == FieldSelectionType.FIELD) subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField()))); else if (fields.get(0).getType() == FieldSelectionType.COMPOSITE_FIELD) { subquery.select(this.manager.getCriteriaBuilder().greatest(this.nestedQueryRoot.get(fields.get(0).getField().split(":")[0]).get(fields.get(0).getField().split(":")[1]))); } return subquery; } }