public static void main(String[] args) { EntityManagerFactory entityManagerFactory = Persistence .createEntityManagerFactory("pl.edu.bogdan.training.db.entity"); EntityManager em = entityManagerFactory.createEntityManager(); em.getTransaction().begin(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<User> cq = cb.createQuery(User.class); Root<User> from = cq.from(User.class); Join<User, Role> join = from.join("role", JoinType.LEFT); cq.where(cb.equal(join.get("name"), "ordinary")); TypedQuery<User> tq = em.createQuery(cq); List<User> users = tq.getResultList(); for (User u : users) { System.out.println(u.getLastName()); } em.getTransaction().commit(); em.close(); entityManagerFactory.close(); }
private Map<Long, Integer> fetchUsedQuotas() { final CriteriaBuilder builder = entityManager.getCriteriaBuilder(); final CriteriaQuery<Tuple> query = builder.createTupleQuery(); final Root<HarvestReport> root = query.from(HarvestReport.class); Join<Harvest, HarvestQuota> joinedQuotas = root.join(HarvestReport_.harvests).join(Harvest_.harvestQuota, JoinType.LEFT); Path<Long> quotaId = joinedQuotas.get(HarvestQuota_.id); Expression<Long> count = builder.count(root.get(HarvestReport_.id)); Predicate onlyApproved = builder.equal(root.get(HarvestReport_.state), HarvestReport.State.APPROVED); Predicate quotaNotNull = builder.isNotNull(quotaId); CriteriaQuery<Tuple> q = query .multiselect(quotaId, count) .where(onlyApproved, quotaNotNull) .groupBy(quotaId); return map(entityManager.createQuery(q).getResultList()); }
private static Predicate createPredicate(Root<Occupation> root, CriteriaBuilder cb, OccupationContactSearchDTO dto) { final List<Predicate> predicates = Lists.newArrayList(); final Join<Occupation, Organisation> organisationJoin = root.join(Occupation_.organisation, JoinType.LEFT); predicates.add(validNow(root, cb)); predicates.add(byOrgType(cb, organisationJoin, dto.getOrganisationType())); if (dto.getAreaCode() != null) { predicates.add(byArea(cb, organisationJoin, dto.getAreaCode())); } if (dto.getRhyCode() != null) { predicates.add(cb.equal(organisationJoin.get(Organisation_.officialCode), dto.getRhyCode())); } if (dto.getOccupationType() != null) { predicates.add(cb.equal(root.get(Occupation_.occupationType), dto.getOccupationType())); } return cb.and(toArray(predicates)); }
private static Optional<MCRUser> getByNaturalID(EntityManager em, String userName, String realmId) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<MCRUser> query = cb.createQuery(MCRUser.class); Root<MCRUser> users = query.from(MCRUser.class); users.fetch(MCRUser_.owner.getName(), JoinType.LEFT); try { return Optional .of(em .createQuery(query .distinct(true) .where(getUserRealmCriterion(cb, users, userName, realmId))) .getSingleResult()); } catch (NoResultException e) { return Optional.empty(); } }
@Override public Object[][] getEntryCourseTableData(SearchFilter filter) throws ProcessingException { Long eventNr = ((SingleEventSearchFormData) filter.getFormData()).getEvent().getValue(); CriteriaBuilder b = JPA.getCriteriaBuilder(); CriteriaQuery<Object[]> selectQuery = b.createQuery(Object[].class); Root<RtCourse> course = selectQuery.from(RtCourse.class); Join<RtCourse, RtEventClass> joinEventClasses = course.join(RtCourse_.rtEventClasses, JoinType.LEFT); Join<RtEventClass, RtRace> joinRaces = joinEventClasses.join(RtEventClass_.rtRaces, JoinType.LEFT); selectQuery.select(b.array(course.get(RtCourse_.id).get(RtCourseKey_.courseNr), course.get(RtCourse_.shortcut), b.countDistinct(joinRaces.get(RtRace_.entryNr)), b.countDistinct(joinRaces.get(RtRace_.id).get(RtRaceKey_.raceNr)))).where(eventNr != null ? b.equal(joinRaces.get(RtRace_.eventNr), eventNr) : b.conjunction()).groupBy(course.get(RtCourse_.id).get(RtCourseKey_.courseNr), course.get(RtCourse_.shortcut)); List<Object[]> list = JPA.createQuery(selectQuery).getResultList(); List<Object[]> result = new ArrayList<>(); for (Object[] row : list) { Object[] resultRow = new Object[5]; resultRow[0] = 0L; // Force Summary Order to bottom resultRow[1] = row[0]; resultRow[2] = row[1]; resultRow[3] = row[2]; resultRow[4] = row[3]; result.add(resultRow); } return JPAUtility.convertList2Array(result); }
@Override public boolean existsRaceWithStartTime(Long[] startlistSettingNrs) throws ProcessingException { if (startlistSettingNrs == null || startlistSettingNrs.length == 0) { return false; } CriteriaBuilder b = JPA.getCriteriaBuilder(); CriteriaQuery<Long> selectQuery = b.createQuery(Long.class); Root<RtParticipation> participation = selectQuery.from(RtParticipation.class); Join<RtParticipation, RtEventClass> joinEventClass = participation.join(RtParticipation_.rtEventClass, JoinType.INNER); Join<RtEventClass, RtCourse> joinCourse = joinEventClass.join(RtEventClass_.rtCourse, JoinType.LEFT); selectQuery.select(b.count(participation.get(RtParticipation_.id).get(RtParticipationKey_.clientNr))) .where( b.and( b.isNotNull(participation.get(RtParticipation_.startTime)), b.equal(participation.get(RtParticipation_.id).get(RtParticipationKey_.clientNr), ServerSession.get().getSessionClientNr()), b.or(joinCourse.get(RtCourse_.startlistSettingNr).in(Arrays.asList(startlistSettingNrs)), joinEventClass.get(RtEventClass_.startlistSettingNr).in(Arrays.asList(startlistSettingNrs))) )); List<Long> result = JPA.createQuery(selectQuery).getResultList(); if (result == null || result.isEmpty()) { return false; } return result.get(0) > 0; }
@Override public List<RtMap> getMapTableData(Long eventNr) throws ProcessingException { CriteriaBuilder b = JPA.getCriteriaBuilder(); CriteriaQuery<RtMap> select = b.createQuery(RtMap.class); Root<RtMap> rtmap = select.from(RtMap.class); List<Predicate> list = new ArrayList<>(); Predicate restriction1 = b.equal(rtmap.get(RtMap_.key).get(RtMapKey_.clientNr), ServerSession.get().getSessionClientNr()); list.add(restriction1); if (eventNr != null) { Join<RtMap, RtEventMap> joinEventMap = rtmap.join(RtMap_.rtEventMaps, JoinType.LEFT); Predicate restriction2 = b.equal(joinEventMap.get(RtEventMap_.id).get(RtEventMapKey_.eventNr), eventNr); list.add(restriction2); } select.where(b.and(list.toArray(new Predicate[list.size()]))); return JPA.createQuery(select).getResultList(); }
@Override public Object[][] getRankingClassesTableData(Long rankingNr) throws ProcessingException { CriteriaBuilder b = JPA.getCriteriaBuilder(); CriteriaQuery<Object[]> selectQuery = b.createQuery(Object[].class); Root<RtRankingEvent> rankingEvent = selectQuery.from(RtRankingEvent.class); Join<RtRankingEvent, RtEvent> joinEvent = rankingEvent.join(RtRankingEvent_.rtEvent, JoinType.INNER); Join<RtEvent, RtEventClass> joinEventClass = joinEvent.join(RtEvent_.rtEventClasses, JoinType.INNER); Subquery<Long> numberOfEventsSubselect = selectQuery.subquery(Long.class); Root<RtRankingEvent> subroot = numberOfEventsSubselect.from(RtRankingEvent.class); numberOfEventsSubselect.select(b.count(subroot.get(RtRankingEvent_.id).get(RtRankingEventKey_.rankingNr))).where(b.and(b.equal(subroot.get(RtRankingEvent_.id).get(RtRankingEventKey_.rankingNr), rankingNr), b.equal(subroot.get(RtRankingEvent_.id).get(RtRankingEventKey_.clientNr), ServerSession.get().getSessionClientNr()))); selectQuery.select(b.array(joinEventClass.get(RtEventClass_.id).get(RtEventClassKey_.classUid), b.count(rankingEvent.get(RtRankingEvent_.id).get(RtRankingEventKey_.eventNr)))).where(b.and(b.equal(rankingEvent.get(RtRankingEvent_.id).get(RtRankingEventKey_.rankingNr), rankingNr), b.equal(rankingEvent.get(RtRankingEvent_.id).get(RtRankingEventKey_.clientNr), ServerSession.get().getSessionClientNr()))).groupBy(joinEventClass.get(RtEventClass_.id).get(RtEventClassKey_.classUid)).having(b.equal(b.count(rankingEvent.get(RtRankingEvent_.id).get(RtRankingEventKey_.eventNr)), numberOfEventsSubselect)); return JPAUtility.convertList2Array(JPA.createQuery(selectQuery).getResultList()); }
@Override public Object[][] getCityTableData(CitySearchFormData formData) throws ProcessingException { CriteriaBuilder b = JPA.getCriteriaBuilder(); CriteriaQuery<Object[]> selectQuery = b.createQuery(Object[].class); Root<RtCity> city = selectQuery.from(RtCity.class); Join<RtCity, RtCountry> joinCountry = city.join(RtCity_.rtCountry); Join<RtCity, RtAddress> joinAddress = city.join(RtCity_.rtAddresses, JoinType.LEFT); JPACityBoxSearchFormDataStatementBuilder builder = new JPACityBoxSearchFormDataStatementBuilder(city); builder.build(formData.getCityBox()); selectQuery.select(b.array(city.get(RtCity_.id).get(RtCityKey_.cityNr), city.get(RtCity_.zip), city.get(RtCity_.name), city.get(RtCity_.areaUid), city.get(RtCity_.region), city.get(RtCity_.countryUid), joinCountry.get(RtCountry_.countryCode), b.count(joinAddress.get(RtAddress_.id).get(RtAddressKey_.addressNr)))).where(b.and(b.equal(city.get(RtCity_.id).get(RtCityKey_.clientNr), ServerSession.get().getSessionClientNr()), builder.getPredicate())).groupBy(city.get(RtCity_.id).get(RtCityKey_.cityNr), city.get(RtCity_.zip), city.get(RtCity_.name), city.get(RtCity_.areaUid), city.get(RtCity_.region), city.get(RtCity_.countryUid), joinCountry.get(RtCountry_.countryCode)); List<Object[]> result = JPA.createQuery(selectQuery).getResultList(); return JPAUtility.convertList2Array(result); }
/** * A {@link Specification} to filter Drops that have been imported or not. * * @param imported {@code true} to get Drops that have been imported, * {@code false} to get Drops that have not yet been imported * * @return {@link Specification} */ public static SingleParamSpecification<Drop> isImported(final Boolean imported) { return new SingleParamSpecification<Drop>(imported) { @Override public Predicate toPredicate(Root<Drop> root, CriteriaQuery<?> query, CriteriaBuilder builder) { Predicate predicate; if (imported) { predicate = builder.and(builder.isNotNull(root.get(Drop_.lastImportedDate)), builder.or(builder.isNull(root.get(Drop_.importFailed)), builder.isFalse(root.get(Drop_.importFailed))), builder.isNotNull(root.get(Drop_.importPollableTask)), builder.isNotNull(root.join(Drop_.importPollableTask, JoinType.LEFT).get(PollableTask_.finishedDate))); } else { predicate = builder.or(builder.isNull(root.get(Drop_.lastImportedDate)), builder.isTrue(root.get(Drop_.importFailed)), builder.isNull(root.get(Drop_.importPollableTask)), builder.isNull(root.join(Drop_.importPollableTask, JoinType.LEFT).get(PollableTask_.finishedDate))); } return predicate; } }; }
protected P filterSpecListToPredicate(MetaDataObject rootMeta, F root, FilterSpec fs, JoinType defaultPredicateJoinType) { if ((fs.getOperator() == FilterOperator.EQ || fs.getOperator() == FilterOperator.NEQ) && fs.getValue() instanceof Collection && ((Collection<?>) fs.getValue()).size() > PARAM_LIMIT_FOR_ORACLE) { return filterLargeValueSets(fs, rootMeta, root, defaultPredicateJoinType); } else { if (fs.hasExpressions()) { return filterExpressions(fs, rootMeta, root, defaultPredicateJoinType); } else { return filterSimpleOperation(fs, rootMeta); } } }
private P filterExpressions(FilterSpec fs, MetaDataObject rootMeta, F root, JoinType defaultPredicateJoinType) { // and, or, not. if (fs.getOperator() == FilterOperator.NOT) { return backend.not( backend.and(filterSpecListToPredicateArray(rootMeta, root, fs.getExpression(), defaultPredicateJoinType))); } else if (fs.getOperator() == FilterOperator.AND) { return backend.and(filterSpecListToPredicateArray(rootMeta, root, fs.getExpression(), defaultPredicateJoinType)); } else if (fs.getOperator() == FilterOperator.OR) { return backend.or(filterSpecListToPredicateArray(rootMeta, root, fs.getExpression(), defaultPredicateJoinType)); } else { throw new IllegalArgumentException(fs.toString()); } }
@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 testJoinType() { // note one entity has no relation assertEquals(4, builder().setDefaultJoinType(JoinType.INNER) .addSortBy(Arrays.asList(TestEntity.ATTR_oneRelatedValue, RelatedEntity.ATTR_id), Direction.ASC) .buildExecutor().getResultList().size()); assertEquals(5, builder().setDefaultJoinType(JoinType.LEFT) .addSortBy(Arrays.asList(TestEntity.ATTR_oneRelatedValue, RelatedEntity.ATTR_id), Direction.ASC) .buildExecutor().getResultList().size()); assertEquals(4, builder().setJoinType(Arrays.asList(TestEntity.ATTR_oneRelatedValue), JoinType.INNER) .addSortBy(Arrays.asList(TestEntity.ATTR_oneRelatedValue, RelatedEntity.ATTR_id), Direction.ASC) .buildExecutor().getResultList().size()); assertEquals(5, builder().setJoinType(Arrays.asList(TestEntity.ATTR_oneRelatedValue), JoinType.LEFT) .addSortBy(Arrays.asList(TestEntity.ATTR_oneRelatedValue, RelatedEntity.ATTR_id), Direction.ASC) .buildExecutor().getResultList().size()); }
@Test public void criteria() { CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<ClientEntityBrowserDto> c = cb.createQuery(ClientEntityBrowserDto.class); Root<Client> client = c.from(Client.class); Join<Client, ClientGroup> clientGroup = client.join("group", JoinType.LEFT); Join<Client, ClientStructure> clientStructure = client.join("structure", JoinType.LEFT); Join<ClientType, ClientTypeGroup> clientTypeGroup = client.join("type", JoinType.LEFT).join("clientTypeGroup", JoinType.LEFT); Selection<ClientEntityBrowserDto> selection = cb.construct(ClientEntityBrowserDto.class, client.<Integer>get("id"), client.<String>get("number"), client.<String>get("name"), clientTypeGroup.<String>get("name"), clientGroup.<String>get("name"), clientStructure.<String>get("name")); c.select(selection); c.distinct(true); TypedQuery<ClientEntityBrowserDto> query = entityManager.createQuery(c); assertTrue(query.getResultList().isEmpty()); }
@Override @SuppressWarnings( "unchecked" ) public List<T> getAllByAttributes( List<Attribute> attributes ) { Schema schema = schemaService.getDynamicSchema( getClazz() ); if ( schema == null || !schema.havePersistedProperty( "attributeValues" ) || attributes.isEmpty() ) { return new ArrayList<>(); } query = getCriteriaQuery(); Root root = query.from( getClazz() ); Join joinAttributeValue = root.join( ("attributeValues"), JoinType.INNER ); query.select( root ); query.where( joinAttributeValue.get( "attribute" ).in( attributes ) ); return sessionFactory.getCurrentSession().createQuery( query ).list(); }
@Override @SuppressWarnings( "unchecked" ) public List<AttributeValue> getAttributeValueByAttribute( Attribute attribute ) { Schema schema = schemaService.getDynamicSchema( getClazz() ); if ( schema == null || !schema.havePersistedProperty( "attributeValues" ) ) { return new ArrayList<>(); } query = getCriteriaQuery(); Root root = query.from( getClazz() ); Join joinAttributeValue = root.join( ("attributeValues"), JoinType.INNER ); query.select( root.get( "attributeValues" ) ); query.where( builder.equal( joinAttributeValue.get( "attribute" ), attribute ) ); return sessionFactory.getCurrentSession().createQuery( query ).list(); }
@Override @SuppressWarnings( "unchecked" ) public List<AttributeValue> getAttributeValueByAttributeAndValue( Attribute attribute, String value ) { Schema schema = schemaService.getDynamicSchema( getClazz() ); if ( schema == null || !schema.havePersistedProperty( "attributeValues" ) ) { return null; } query = getCriteriaQuery(); Root root = query.from( getClazz() ); Join joinAttributeValue = root.join( ("attributeValues"), JoinType.INNER ); query.select( root.get( "attributeValues" ) ); query.where( builder.and( builder.equal( joinAttributeValue.get( "attribute" ), attribute ), builder.equal( joinAttributeValue.get( "value" ), value ) ) ); return sessionFactory.getCurrentSession().createQuery( query ).list(); }
@Override public Page<String> findMessagesByActionStatusId(final Pageable pageable, final Long actionStatusId) { final CriteriaBuilder cb = entityManager.getCriteriaBuilder(); final CriteriaQuery<Long> countMsgQuery = cb.createQuery(Long.class); final Root<JpaActionStatus> countMsgQueryFrom = countMsgQuery.distinct(true).from(JpaActionStatus.class); final ListJoin<JpaActionStatus, String> cJoin = countMsgQueryFrom.joinList("messages", JoinType.LEFT); countMsgQuery.select(cb.count(cJoin)) .where(cb.equal(countMsgQueryFrom.get(JpaActionStatus_.id), actionStatusId)); final Long totalCount = entityManager.createQuery(countMsgQuery).getSingleResult(); final CriteriaQuery<String> msgQuery = cb.createQuery(String.class); final Root<JpaActionStatus> as = msgQuery.from(JpaActionStatus.class); final ListJoin<JpaActionStatus, String> join = as.joinList("messages", JoinType.LEFT); final CriteriaQuery<String> selMsgQuery = msgQuery.select(join); selMsgQuery.where(cb.equal(as.get(JpaActionStatus_.id), actionStatusId)); final List<String> result = entityManager.createQuery(selMsgQuery).setFirstResult(pageable.getOffset()) .setMaxResults(pageable.getPageSize()).getResultList().stream().collect(Collectors.toList()); return new PageImpl<>(result, pageable, totalCount); }
@Override public <Y> JpaFetch<X, Y> fetch(PluralAttribute<? super X, ?, Y> pluralAttribute, JoinType jt) { // if ( !canBeFetchSource() ) { // throw illegalFetch(); // } // // final Fetch<X, Y> fetch; // // TODO : combine Fetch and Join hierarchies (JoinImplementor extends Join,Fetch???) // if ( PluralAttribute.CollectionType.COLLECTION.equals( pluralAttribute.getCollectionType() ) ) { // fetch = constructJoin( (CollectionAttribute<X, Y>) pluralAttribute, jt ); // } // else if ( PluralAttribute.CollectionType.LIST.equals( pluralAttribute.getCollectionType() ) ) { // fetch = constructJoin( (ListAttribute<X, Y>) pluralAttribute, jt ); // } // else if ( PluralAttribute.CollectionType.SET.equals( pluralAttribute.getCollectionType() ) ) { // fetch = constructJoin( (SetAttribute<X, Y>) pluralAttribute, jt ); // } // else { // fetch = constructJoin( (MapAttribute<X, ?, Y>) pluralAttribute, jt ); // } // joinScope.addFetch( fetch ); // return fetch; throw new NotYetImplementedException( ); }
@Override public DynamicResultSet fetch(PersistencePackage persistencePackage, CriteriaTransferObject cto, DynamicEntityDao dynamicEntityDao, RecordHelper helper) throws ServiceException { cto.getNonCountAdditionalFilterMappings().add(new FilterMapping() .withDirectFilterValues(new EmptyFilterValues()) .withRestriction(new Restriction() .withPredicateProvider(new PredicateProvider() { public Predicate buildPredicate(CriteriaBuilder builder, FieldPathBuilder fieldPathBuilder, From root, String ceilingEntity, String fullPropertyName, Path explicitPath, List directValues) { root.fetch("defaultSku", JoinType.LEFT); root.fetch("defaultCategory", JoinType.LEFT); return null; } }) )); return helper.getCompatibleModule(OperationType.BASIC).fetch(persistencePackage, cto); }
private Predicate createCompositeParamPart(CriteriaBuilder builder, Root<ResourceTable> from, RuntimeSearchParam left, IQueryParameterType leftValue) { Predicate retVal = null; switch (left.getParamType()) { case STRING: { From<ResourceIndexedSearchParamString, ResourceIndexedSearchParamString> stringJoin = from.join("myParamsString", JoinType.INNER); retVal = createPredicateString(leftValue, left.getName(), builder, stringJoin); break; } case TOKEN: { From<ResourceIndexedSearchParamToken, ResourceIndexedSearchParamToken> tokenJoin = from.join("myParamsToken", JoinType.INNER); retVal = createPredicateToken(leftValue, left.getName(), builder, tokenJoin); break; } case DATE: { From<ResourceIndexedSearchParamDate, ResourceIndexedSearchParamDate> dateJoin = from.join("myParamsDate", JoinType.INNER); retVal = createPredicateDate(builder, dateJoin, leftValue); break; } } if (retVal == null) { throw new InvalidRequestException("Don't know how to handle composite parameter with type of " + left.getParamType()); } return retVal; }
@SuppressWarnings("unchecked") public <E, F> Path<F> getPath(Root<E> root, List<Attribute<?, ?>> attributes) { Path<?> path = root; for (Attribute<?, ?> attribute : attributes) { boolean found = false; if (path instanceof FetchParent) { for (Fetch<E, ?> fetch : ((FetchParent<?, E>) path).getFetches()) { if (attribute.getName().equals(fetch.getAttribute().getName()) && (fetch instanceof Join<?, ?>)) { path = (Join<E, ?>) fetch; found = true; break; } } } if (!found) { if ((attributes.indexOf(attribute) != (attributes.size() - 1)) && (attribute instanceof Bindable) && Identifiable.class.isAssignableFrom(((Bindable<?>) attribute).getBindableJavaType()) && (path instanceof From)) { path = ((From<?, ?>) path).join(attribute.getName(), JoinType.LEFT); } else { path = path.get(attribute.getName()); } } } return (Path<F>) path; }
@SuppressWarnings({ "unchecked", "rawtypes" }) public <E> void fetches(SearchParameters<E> sp, Root<E> root) { for (jpasearch.repository.query.Path<E, ?> path : sp.getFetches()) { FetchParent<?, ?> from = root; for (Attribute<?, ?> arg : metamodelUtil.toAttributes(root.getJavaType(), path.getPath())) { boolean found = false; for (Fetch<?, ?> fetch : from.getFetches()) { if (arg.equals(fetch.getAttribute())) { from = fetch; found = true; break; } } if (!found) { if (arg instanceof PluralAttribute) { from = from.fetch((PluralAttribute) arg, JoinType.LEFT); } else { from = from.fetch((SingularAttribute) arg, JoinType.LEFT); } } } } }
@Override public Optional<NestedNodeInfo<N>> getNodeInfo(Long nodeId, Class<N> nodeClass) { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<NestedNodeInfo> select = cb.createQuery(NestedNodeInfo.class); Root<N> root = select.from(nodeClass); Join<N, N> parent = root.join(parent(nodeClass), JoinType.LEFT); select.select( cb.construct( NestedNodeInfo.class, root.<Long>get(id(nodeClass)), parent.<Long>get(id(nodeClass)), root.<Long>get(left(nodeClass)), root.<Long>get(right(nodeClass)), root.<Long>get(level(nodeClass)) ) ).where(cb.equal(root.<Long>get(id(nodeClass)), nodeId)); try { NestedNodeInfo<N> result = em.createQuery(select).getSingleResult(); result.setNodeClass(nodeClass); return Optional.of(result); } catch (NoResultException ex) { return Optional.<NestedNodeInfo<N>>empty(); } }
/** * fetch join: * SELECT e FROM jpa_query_employee e JOIN FETCH e.address */ // @Transactional public void doFrom3(){ CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Employee> c = cb.createQuery(Employee.class); Root<Employee> e = c.from(Employee.class); e.fetch("address"); e.fetch("department"); e.fetch("projects",JoinType.INNER); // e.fetch("phones"); // e.fetch("directs"); // e.fetch("manager"); c.select(e); // only show the fetched data TypedQuery<Employee> query = em.createQuery(c); List<Employee> result = query.getResultList(); for(Employee emp : result){ System.out.println(emp.getId() + " | " + emp.getName() + " | " + emp.getAddress() + " | " + emp.getDepartment() + " | " + emp.getProjects()); } }
@Override @Transactional(readOnly = true) public List<BookingDTO> findNotUsedAndExpiredBookings(List<String> ixsiBookingIdList) { CriteriaBuilder builder = em.getCriteriaBuilder(); CriteriaQuery<BookingDTO> criteria = builder.createQuery(BookingDTO.class); Root<Booking> booking = criteria.from(Booking.class); Join<Booking, Reservation> reservation = booking.join(Booking_.reservation, JoinType.INNER); criteria.select( builder.construct( BookingDTO.class, booking.get(Booking_.ixsiBookingId), reservation.get(Reservation_.startDateTime) ) ); criteria.where( builder.and( booking.get(Booking_.ixsiBookingId).in(ixsiBookingIdList), booking.get(Booking_.transaction).isNull(), builder.lessThan(reservation.get(Reservation_.endDateTime), new LocalDateTime()) )); return em.createQuery(criteria).getResultList(); }
@Test public void resolvesJoinFetchForSimpleSpec() throws Exception { MethodParameter param = MethodParameter.forMethodOrConstructor(testMethod("testMethod"), 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(resolved) .isInstanceOf(Conjunction.class); Collection<Specification<?>> innerSpecs = ReflectionUtils.get(resolved, "innerSpecs"); assertThat(innerSpecs) .hasSize(2) .contains(new Like<Object>(queryCtx, "path1", new String[] { "value1" })) .contains(new net.kaczmarzyk.spring.data.jpa.domain.JoinFetch<Object>(new String[] { "fetch1", "fetch2" }, JoinType.LEFT)); }
@Test public void resolvesJoinContainerWithJoinFetch() throws Exception { MethodParameter param = MethodParameter.forMethodOrConstructor(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(resolved) .isInstanceOf(Conjunction.class); Collection<Specification<?>> innerSpecs = ReflectionUtils.get(resolved, "innerSpecs"); assertThat(innerSpecs) .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))); }
@Test public void resolvesJoinContainerWithRegularJoin() throws Exception { MethodParameter param = MethodParameter.forMethodOrConstructor(testMethod("testMethod_joinContainerWithRegularJoin"), 0); FakeWebRequest req = new FakeWebRequest(); QueryContext queryCtx = new WebRequestQueryContext(req); req.setParameterValues("path1", "value1"); Specification<?> resolved = (Specification<?>) resolver.resolveArgument(param, null, req, null); assertThat(resolved) .isInstanceOf(Conjunction.class); Collection<Specification<?>> innerSpecs = ReflectionUtils.get(resolved, "innerSpecs"); assertThat(innerSpecs) .hasSize(2) .contains(new Like<Object>(queryCtx, "path1", new String[] { "value1" })) .contains(new Conjunction<Object>( new net.kaczmarzyk.spring.data.jpa.domain.Join<Object>(queryCtx, "join1", "alias1", JoinType.INNER, true), new net.kaczmarzyk.spring.data.jpa.domain.Join<Object>(queryCtx, "join2", "alias2", JoinType.LEFT, false))); }
@Test public void resolvesJoinContainerWithRegularAndFetchJoins() throws Exception { MethodParameter param = MethodParameter.forMethodOrConstructor(testMethod("testMethod_joinContainerWithRegularAndFetchJoins"), 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(resolved) .isInstanceOf(Conjunction.class); Collection<Specification<?>> innerSpecs = ReflectionUtils.get(resolved, "innerSpecs"); assertThat(innerSpecs) .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), new net.kaczmarzyk.spring.data.jpa.domain.Join<Object>(queryCtx, "join1", "alias1", JoinType.INNER, true), new net.kaczmarzyk.spring.data.jpa.domain.Join<Object>(queryCtx, "join2", "alias2", JoinType.LEFT, false))); }
@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 protected Predicate createAreaPredicate(final CriteriaBuilder cb, final Root objectRoot, Predicate predicate, final Set permitRegions, final Set permitBrands) { if (!permitRegions.isEmpty()) { final Predicate regPredicate = objectRoot.get(LegalEntity_.legalAddress) .get(Address_.regionWithType) .in(permitRegions); predicate = predicate == null ? regPredicate : cb.and(predicate, regPredicate); } if (!permitBrands.isEmpty()) { final Predicate brPredicate = objectRoot.join(LegalEntity_.motorBrands, JoinType.LEFT) .in(permitBrands); predicate = predicate == null ? brPredicate : cb.and(predicate, brPredicate); } return predicate; }
private F getOrCreateJoin(MetaAttributePath srcPath, MetaAttribute targetAttr) { MetaAttributePath path = srcPath.concat(targetAttr); F parent = joinMap.get(srcPath); F join = joinMap.get(path); if (join == null) { JoinType joinType = query.getJoinType(path); join = backend.doJoin(targetAttr, joinType, parent); joinMap.put(path, join); } return join; }
public List<P> filterSpecListToPredicateArray(MetaDataObject rootMeta, F root, List<FilterSpec> rowFilters, JoinType defaultPredicateJoinType) { ArrayList<P> predicateList = new ArrayList<>(); for (FilterSpec rowFilter : rowFilters) { predicateList.add(filterSpecListToPredicate(rootMeta, root, rowFilter, defaultPredicateJoinType)); } return predicateList; }
private P filterLargeValueSets(FilterSpec filterSpec, MetaDataObject rootMeta, F root, JoinType defaultPredicateJoinType) { // Split filter values with two many elements. Oracle is limited to 1000. ArrayList<FilterSpec> filterSpecs = new ArrayList<>(); List<?> list = new ArrayList<>((Collection<?>) filterSpec.getValue()); for (int i = 0; i < list.size(); i += PARAM_LIMIT_FOR_ORACLE) { int nextOffset = i + Math.min(list.size() - i, PARAM_LIMIT_FOR_ORACLE); List<?> batchList = list.subList(i, nextOffset); filterSpecs.add(new FilterSpec(filterSpec.getAttributePath(), filterSpec.getOperator(), batchList)); } FilterSpec orSpec = FilterSpec.or(filterSpecs); return filterSpecListToPredicate(rootMeta, root, orSpec, defaultPredicateJoinType); }
public static com.querydsl.core.JoinType convertJoinType(JoinType joinType) { switch (joinType) { case INNER: return com.querydsl.core.JoinType.JOIN; case LEFT: return com.querydsl.core.JoinType.LEFTJOIN; case RIGHT: return com.querydsl.core.JoinType.RIGHTJOIN; default: throw new IllegalStateException(joinType.toString() + " unknown"); } }