use of org.eclipse.persistence.queries.ReadQuery in project eclipselink by eclipse-ee4j.
the class EntityManagerFactoryImpl method addNamedQuery.
@Override
public void addNamedQuery(String name, Query query) {
QueryImpl queryImpl = query.unwrap(QueryImpl.class);
DatabaseQuery unwrapped = (DatabaseQuery) queryImpl.getDatabaseQueryInternal().clone();
if (queryImpl.lockMode != null) {
((ObjectLevelReadQuery) unwrapped).setLockModeType(queryImpl.lockMode.name(), getServerSession());
}
if (unwrapped.isReadQuery()) {
((ReadQuery) unwrapped).setInternalMax((queryImpl.getMaxResultsInternal()));
((ReadQuery) unwrapped).setFirstResult((queryImpl.getFirstResult()));
}
this.getServerSession().addQuery(name, unwrapped, true);
}
use of org.eclipse.persistence.queries.ReadQuery in project eclipselink by eclipse-ee4j.
the class AbstractEntityResource method findAttributeInternal.
protected Response findAttributeInternal(String version, String persistenceUnit, String type, String id, String attribute, HttpHeaders headers, UriInfo uriInfo) {
JPARSLogger.entering(CLASS_NAME, "findAttributeInternal", new Object[] { "GET", version, persistenceUnit, type, id, attribute, uriInfo.getRequestUri().toASCIIString() });
EntityManager em = null;
try {
PersistenceContext context = getPersistenceContext(persistenceUnit, type, uriInfo.getBaseUri(), version, null);
Object entityId = IdHelper.buildId(context, type, id);
em = context.getEmf().createEntityManager(getMatrixParameters(uriInfo, persistenceUnit));
Object entity = em.find(context.getClass(type), entityId, getQueryParameters(uriInfo));
DatabaseSession serverSession = context.getServerSession();
ClassDescriptor descriptor = serverSession.getClassDescriptor(context.getClass(type));
if (descriptor == null) {
throw JPARSException.classOrClassDescriptorCouldNotBeFoundForEntity(type, persistenceUnit);
}
DatabaseMapping attributeMapping = descriptor.getMappingForAttributeName(attribute);
if ((attributeMapping == null) || (entity == null)) {
throw JPARSException.databaseMappingCouldNotBeFoundForEntityAttribute(attribute, type, id, persistenceUnit);
}
if (!attributeMapping.isCollectionMapping()) {
Object result = attributeMapping.getRealAttributeValueFromAttribute(attributeMapping.getAttributeValueFromObject(entity), entity, (AbstractSession) serverSession);
if (result == null) {
JPARSLogger.error(context.getSessionLog(), "jpars_could_not_find_entity_for_attribute", new Object[] { attribute, type, id, persistenceUnit });
throw JPARSException.attributeCouldNotBeFoundForEntity(attribute, type, id, persistenceUnit);
}
final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, responseBuilder, null);
}
ReadQuery query = (ReadQuery) ((((ForeignReferenceMapping) attributeMapping).getSelectionQuery()).clone());
if (query == null) {
throw JPARSException.selectionQueryForAttributeCouldNotBeFoundForEntity(attribute, type, id, persistenceUnit);
}
final FeatureSet featureSet = context.getSupportedFeatureSet();
final AbstractSession clientSession = context.getClientSession(em);
// Fields filtering
FieldsFilter fieldsFilter = null;
if (context.getSupportedFeatureSet().isSupported(Feature.FIELDS_FILTERING)) {
final FieldsFilteringValidator fieldsFilteringValidator = new FieldsFilteringValidator(uriInfo);
if (fieldsFilteringValidator.isFeatureApplicable()) {
fieldsFilter = fieldsFilteringValidator.getFilter();
}
}
// Pagination
if (featureSet.isSupported(Feature.PAGING)) {
final PageableFieldValidator validator = new PageableFieldValidator(entity.getClass(), attribute, uriInfo);
if (validator.isFeatureApplicable()) {
// Adding extra one to detect are there more rows or not. It will be removed later
// on in response processor.
query.setMaxRows(validator.getLimit() + validator.getOffset() + 1);
query.setFirstResult(validator.getOffset());
// We need to add limit and offset to query parameters because request builder reads it from there
final Map<String, Object> queryParams = getQueryParameters(uriInfo);
queryParams.put(QueryParameters.JPARS_PAGING_LIMIT, String.valueOf(validator.getLimit()));
queryParams.put(QueryParameters.JPARS_PAGING_OFFSET, String.valueOf(validator.getOffset()));
// check orderBy, and generate a warning if there is none
checkOrderBy(context, query);
final Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.PAGING);
return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, queryParams, headers, uriInfo, responseBuilder, fieldsFilter);
}
}
final Object result = clientSession.executeQuery(query, descriptor.getObjectBuilder().buildRow(entity, clientSession, WriteType.INSERT));
final FeatureResponseBuilder responseBuilder = context.getSupportedFeatureSet().getResponseBuilder(Feature.NO_PAGING);
return findAttributeResponse(context, attribute, type, id, persistenceUnit, result, getQueryParameters(uriInfo), headers, uriInfo, responseBuilder, fieldsFilter);
} catch (Exception ex) {
throw JPARSException.exceptionOccurred(ex);
} finally {
if (em != null) {
if (em.isOpen()) {
em.close();
}
}
}
}
use of org.eclipse.persistence.queries.ReadQuery in project eclipselink by eclipse-ee4j.
the class ExpressionBuilder method normalize.
/**
* INTERNAL:
* Normalize the expression into a printable structure.
* Any joins must be added to form a new root.
*/
@Override
public Expression normalize(ExpressionNormalizer normalizer) {
if (hasBeenNormalized()) {
return this;
} else {
setHasBeenNormalized(true);
}
// Normalize the ON clause if present. Need to use rebuild, not twist as parameters are real parameters.
if (this.onClause != null) {
this.onClause = this.onClause.normalize(normalizer);
if (shouldUseOuterJoin() || (!getSession().getPlatform().shouldPrintInnerJoinInWhereClause())) {
normalizer.getStatement().addOuterJoinExpressionsHolders(this, null, null, null);
if ((getDescriptor() != null) && (getDescriptor().getHistoryPolicy() != null)) {
Expression historyCriteria = getDescriptor().getHistoryPolicy().additionalHistoryExpression(this, this);
if (historyCriteria != null) {
normalizer.addAdditionalExpression(historyCriteria);
}
}
} else {
normalizer.addAdditionalExpression(this.onClause);
}
}
// the session must be set and the additional join expression added.
if (this.queryClass != null) {
Expression criteria = null;
setSession(normalizer.getSession().getRootSession(null));
// The descriptor must be defined at this point.
if (getDescriptor() == null) {
throw QueryException.noExpressionBuilderFound(this);
}
if (!this.wasAdditionJoinCriteriaUsed) {
criteria = getDescriptor().getQueryManager().getAdditionalJoinExpression();
if (criteria != null) {
criteria = twist(criteria, this);
}
}
if (isUsingOuterJoinForMultitableInheritance()) {
if (getSession().getPlatform().shouldPrintOuterJoinInWhereClause()) {
Expression childrenCriteria = getDescriptor().getInheritancePolicy().getChildrenJoinExpression();
childrenCriteria = twist(childrenCriteria, this);
childrenCriteria.convertToUseOuterJoin();
if (criteria == null) {
criteria = childrenCriteria;
} else {
criteria = criteria.and(childrenCriteria);
}
} else {
normalizer.getStatement().addOuterJoinExpressionsHolders(null, null, additionalExpressionCriteriaMap(), this.getDescriptor());
// fall through to the main case
}
}
normalizer.addAdditionalExpression(criteria);
}
setStatement(normalizer.getStatement());
if (getAsOfClause() == null) {
asOf(AsOfClause.NO_CLAUSE);
}
if ((getDescriptor() != null) && (getDescriptor().getHistoryPolicy() != null)) {
Expression temporalCriteria = getDescriptor().getHistoryPolicy().additionalHistoryExpression(this, this);
normalizer.addAdditionalExpression(temporalCriteria);
}
ReadQuery query = normalizer.getStatement().getQuery();
// Record any class used in a join to invalidate query results cache.
if ((query != null) && query.shouldCacheQueryResults()) {
if (this.queryClass != null) {
query.getQueryResultsCachePolicy().getInvalidationClasses().add(this.queryClass);
}
}
return this;
}
use of org.eclipse.persistence.queries.ReadQuery in project eclipselink by eclipse-ee4j.
the class EISObjectPersistenceXMLProject method buildEISOneToManyMappingDescriptor.
protected ClassDescriptor buildEISOneToManyMappingDescriptor() {
XMLDescriptor descriptor = new XMLDescriptor();
descriptor.setJavaClass(EISOneToManyMapping.class);
XMLCompositeCollectionMapping foreignKeyFieldNamesMapping = new XMLCompositeCollectionMapping();
foreignKeyFieldNamesMapping.setAttributeName("sourceForeignKeyFields");
foreignKeyFieldNamesMapping.useCollectionClass(java.util.ArrayList.class);
foreignKeyFieldNamesMapping.setGetMethodName("getSourceForeignKeyFields");
foreignKeyFieldNamesMapping.setSetMethodName("setSourceForeignKeyFields");
foreignKeyFieldNamesMapping.setXPath(getPrimaryNamespaceXPath() + "source-foreign-key-fields/" + getPrimaryNamespaceXPath() + "field");
foreignKeyFieldNamesMapping.setReferenceClass(DatabaseField.class);
descriptor.addMapping(foreignKeyFieldNamesMapping);
XMLCompositeCollectionMapping targetForeignKeyFieldNamesMapping = new XMLCompositeCollectionMapping();
targetForeignKeyFieldNamesMapping.setAttributeName("targetForeignKeyFields");
targetForeignKeyFieldNamesMapping.useCollectionClass(java.util.ArrayList.class);
targetForeignKeyFieldNamesMapping.setGetMethodName("getTargetForeignKeyFields");
targetForeignKeyFieldNamesMapping.setSetMethodName("setTargetForeignKeyFields");
targetForeignKeyFieldNamesMapping.setXPath(getPrimaryNamespaceXPath() + "target-foreign-key-fields/" + getPrimaryNamespaceXPath() + "field");
targetForeignKeyFieldNamesMapping.setReferenceClass(DatabaseField.class);
descriptor.addMapping(targetForeignKeyFieldNamesMapping);
XMLCompositeObjectMapping foreignKeyGroupingElementMapping = new XMLCompositeObjectMapping();
foreignKeyGroupingElementMapping.setAttributeName("field");
foreignKeyGroupingElementMapping.setReferenceClass(DatabaseField.class);
foreignKeyGroupingElementMapping.setGetMethodName("getForeignKeyGroupingElement");
foreignKeyGroupingElementMapping.setSetMethodName("setForeignKeyGroupingElement");
foreignKeyGroupingElementMapping.setXPath(getPrimaryNamespaceXPath() + "foreign-key-grouping-element");
descriptor.addMapping(foreignKeyGroupingElementMapping);
XMLDirectMapping relationshipPartnerAttributeNameMapping = new XMLDirectMapping();
relationshipPartnerAttributeNameMapping.setAttributeName("relationshipPartnerAttributeName");
relationshipPartnerAttributeNameMapping.setGetMethodName("getRelationshipPartnerAttributeName");
relationshipPartnerAttributeNameMapping.setSetMethodName("setRelationshipPartnerAttributeName");
relationshipPartnerAttributeNameMapping.setXPath(getPrimaryNamespaceXPath() + "bidirectional-target-attribute/text()");
descriptor.addMapping(relationshipPartnerAttributeNameMapping);
XMLCompositeObjectMapping containerPolicyMapping = new XMLCompositeObjectMapping();
containerPolicyMapping.setAttributeName("collectionPolicy");
containerPolicyMapping.setGetMethodName("getContainerPolicy");
containerPolicyMapping.setSetMethodName("setContainerPolicy");
containerPolicyMapping.setReferenceClass(ContainerPolicy.class);
containerPolicyMapping.setXPath(getPrimaryNamespaceXPath() + "container");
descriptor.addMapping(containerPolicyMapping);
XMLCompositeObjectMapping indirectionPolicyMapping = new XMLCompositeObjectMapping();
indirectionPolicyMapping.setReferenceClass(IndirectionPolicy.class);
// Handle translation of NoIndirectionPolicy -> null.
indirectionPolicyMapping.setAttributeAccessor(new AttributeAccessor() {
@Override
public Object getAttributeValueFromObject(Object object) {
IndirectionPolicy policy = ((ForeignReferenceMapping) object).getIndirectionPolicy();
if (policy instanceof NoIndirectionPolicy) {
return null;
}
return policy;
}
@Override
public void setAttributeValueInObject(Object object, Object value) {
IndirectionPolicy policy = (IndirectionPolicy) value;
if (value == null) {
policy = new NoIndirectionPolicy();
}
((ForeignReferenceMapping) object).setIndirectionPolicy(policy);
}
});
indirectionPolicyMapping.setAttributeName("indirectionPolicy");
indirectionPolicyMapping.setXPath(getPrimaryNamespaceXPath() + "indirection");
descriptor.addMapping(indirectionPolicyMapping);
XMLCompositeObjectMapping selectionQueryMapping = new XMLCompositeObjectMapping();
selectionQueryMapping.setAttributeName("selectionQuery");
selectionQueryMapping.setReferenceClass(ReadQuery.class);
selectionQueryMapping.setAttributeAccessor(new AttributeAccessor() {
@Override
public Object getAttributeValueFromObject(Object object) {
if (((ForeignReferenceMapping) object).hasCustomSelectionQuery()) {
return ((ForeignReferenceMapping) object).getSelectionQuery();
}
return null;
}
@Override
public void setAttributeValueInObject(Object object, Object value) {
if (value instanceof ReadQuery) {
((ForeignReferenceMapping) object).setCustomSelectionQuery((ReadQuery) value);
}
}
});
selectionQueryMapping.setXPath(getPrimaryNamespaceXPath() + "selection-query");
descriptor.addMapping(selectionQueryMapping);
// delete-all query
XMLCompositeObjectMapping deleteAllQueryMapping = new XMLCompositeObjectMapping();
deleteAllQueryMapping.setAttributeName("deleteAllQuery");
deleteAllQueryMapping.setReferenceClass(ModifyQuery.class);
deleteAllQueryMapping.setAttributeAccessor(new AttributeAccessor() {
@Override
public Object getAttributeValueFromObject(Object object) {
boolean hasCustomDeleteAllQuery = ((EISOneToManyMapping) object).hasCustomDeleteAllQuery();
if (hasCustomDeleteAllQuery) {
return ((EISOneToManyMapping) object).getDeleteAllQuery();
} else {
return null;
}
}
@Override
public void setAttributeValueInObject(Object object, Object value) {
if (value instanceof ModifyQuery) {
((EISOneToManyMapping) object).setCustomDeleteAllQuery((ModifyQuery) value);
}
}
});
deleteAllQueryMapping.setXPath(getPrimaryNamespaceXPath() + "delete-all-query");
descriptor.addMapping(deleteAllQueryMapping);
descriptor.getInheritancePolicy().setParentClass(CollectionMapping.class);
return descriptor;
}
use of org.eclipse.persistence.queries.ReadQuery in project eclipselink by eclipse-ee4j.
the class ForeignReferenceMapping method prepareNestedBatchQuery.
/**
* INTERNAL:
* Clone and prepare the selection query as a nested batch read query.
* This is used for nested batch reading.
*/
public ReadQuery prepareNestedBatchQuery(ObjectLevelReadQuery query) {
// For CR#2646-S.M. In case of inheritance the descriptor to use may not be that
// of the source query (the base class descriptor), but that of the subclass, if the
// attribute is only of the subclass. Thus in this case use the descriptor from the mapping.
// Also: for Bug 5478648 - Do not switch the descriptor if the query's descriptor is an aggregate
ClassDescriptor descriptorToUse = query.getDescriptor();
if ((descriptorToUse != this.descriptor) && (!descriptorToUse.getMappings().contains(this)) && (!this.descriptor.isDescriptorTypeAggregate())) {
descriptorToUse = this.descriptor;
}
ExpressionBuilder builder = new ExpressionBuilder(this.referenceClass);
builder.setQueryClassAndDescriptor(this.referenceClass, getReferenceDescriptor());
ReadAllQuery batchQuery = new ReadAllQuery(this.referenceClass, builder);
batchQuery.setName(getAttributeName());
batchQuery.setDescriptor(getReferenceDescriptor());
batchQuery.setSession(query.getSession());
batchQuery.setShouldUseSerializedObjectPolicy(query.shouldUseSerializedObjectPolicy());
// bug 3965568
// we should not wrap the results as this is an internal query
batchQuery.setShouldUseWrapperPolicy(false);
if (query.shouldCascadeAllParts() || (query.shouldCascadePrivateParts() && isPrivateOwned()) || (query.shouldCascadeByMapping() && this.cascadeRefresh)) {
batchQuery.setShouldRefreshIdentityMapResult(query.shouldRefreshIdentityMapResult());
batchQuery.setCascadePolicy(query.getCascadePolicy());
batchQuery.setShouldMaintainCache(query.shouldMaintainCache());
if (query.hasAsOfClause()) {
batchQuery.setAsOfClause(query.getAsOfClause());
}
// bug 3802197 - cascade binding and prepare settings
batchQuery.setShouldBindAllParameters(query.getShouldBindAllParameters());
batchQuery.setShouldPrepare(query.shouldPrepare());
}
batchQuery.setShouldOuterJoinSubclasses(query.shouldOuterJoinSubclasses());
// CR #4365
batchQuery.setQueryId(query.getQueryId());
Expression batchSelectionCriteria = null;
// Build the batch query, either using joining, or an exist sub-select.
BatchFetchType batchType = query.getBatchFetchPolicy().getType();
if (this.batchFetchType != null) {
batchType = this.batchFetchType;
}
if (batchType == BatchFetchType.EXISTS) {
// Using a EXISTS sub-select (WHERE EXIST (<original-query> AND <mapping-join> AND <mapping-join>)
ExpressionBuilder subBuilder = new ExpressionBuilder(descriptorToUse.getJavaClass());
subBuilder.setQueryClassAndDescriptor(descriptorToUse.getJavaClass(), descriptorToUse);
ReportQuery subQuery = new ReportQuery(descriptorToUse.getJavaClass(), subBuilder);
subQuery.setDescriptor(descriptorToUse);
subQuery.setShouldRetrieveFirstPrimaryKey(true);
Expression subCriteria = subBuilder.twist(getSelectionCriteria(), builder);
if (query.getSelectionCriteria() != null) {
// For bug 2612567, any query can have batch attributes, so the
// original selection criteria can be quite complex, with multiple
// builders (i.e. for parallel selects).
// Now uses cloneUsing(newBase) instead of rebuildOn(newBase).
subCriteria = query.getSelectionCriteria().cloneUsing(subBuilder).and(subCriteria);
}
// Check for history and set asOf.
if (descriptorToUse.getHistoryPolicy() != null) {
if (query.getSession().getAsOfClause() != null) {
subBuilder.asOf(query.getSession().getAsOfClause());
} else if (batchQuery.getAsOfClause() == null) {
subBuilder.asOf(AsOfClause.NO_CLAUSE);
} else {
subBuilder.asOf(batchQuery.getAsOfClause());
}
}
subQuery.setSelectionCriteria(subCriteria);
batchSelectionCriteria = builder.exists(subQuery);
} else if (batchType == BatchFetchType.IN) {
// Using a IN with foreign key values (WHERE FK IN :QUERY_BATCH_PARAMETER)
batchSelectionCriteria = buildBatchCriteria(builder, query);
} else {
// Using a join, (WHERE <orginal-query-criteria> AND <mapping-join>)
// Join the query where clause with the mapping's,
// this will cause a join that should bring in all of the target objects.
Expression backRef = builder.getManualQueryKey(getAttributeName() + "-back-ref", descriptorToUse);
batchSelectionCriteria = backRef.twist(getSelectionCriteria(), builder);
if (query.getSelectionCriteria() != null) {
// For bug 2612567, any query can have batch attributes, so the
// original selection criteria can be quite complex, with multiple
// builders (i.e. for parallel selects).
// Now uses cloneUsing(newBase) instead of rebuildOn(newBase).
batchSelectionCriteria = batchSelectionCriteria.and(query.getSelectionCriteria().cloneUsing(backRef));
}
// to somehow keep all this code inside QueryKeyExpression.normalize.
if (descriptorToUse.getQueryManager().getAdditionalJoinExpression() != null) {
batchSelectionCriteria = batchSelectionCriteria.and(descriptorToUse.getQueryManager().getAdditionalJoinExpression().rebuildOn(backRef));
}
// Check for history and add history expression.
if (descriptorToUse.getHistoryPolicy() != null) {
if (query.getSession().getAsOfClause() != null) {
backRef.asOf(query.getSession().getAsOfClause());
} else if (batchQuery.getAsOfClause() == null) {
backRef.asOf(AsOfClause.NO_CLAUSE);
} else {
backRef.asOf(batchQuery.getAsOfClause());
}
batchSelectionCriteria = batchSelectionCriteria.and(descriptorToUse.getHistoryPolicy().additionalHistoryExpression(backRef, backRef));
}
}
batchQuery.setSelectionCriteria(batchSelectionCriteria);
if (query.isDistinctComputed()) {
// Only recompute if it has not already been set by the user
batchQuery.setDistinctState(query.getDistinctState());
}
// Add batch reading attributes contained in the mapping's query.
ReadQuery mappingQuery = this.selectionQuery;
if (mappingQuery.isReadAllQuery()) {
// CR#3238 clone these vectors so they will not grow with each call to the query. -TW
batchQuery.setOrderByExpressions(new ArrayList<>(((ReadAllQuery) mappingQuery).getOrderByExpressions()));
if (((ReadAllQuery) mappingQuery).hasBatchReadAttributes()) {
for (Expression expression : ((ReadAllQuery) mappingQuery).getBatchReadAttributeExpressions()) {
batchQuery.addBatchReadAttribute(expression);
}
}
}
// has been using inheritance and child descriptors can have different mappings.
if (query.hasBatchReadAttributes()) {
for (Expression expression : query.getBatchReadAttributeExpressions()) {
ObjectExpression batchReadExpression = (ObjectExpression) expression;
// Batch Read Attribute Expressions may not have initialized.
ExpressionBuilder expressionBuilder = batchReadExpression.getBuilder();
if (expressionBuilder.getQueryClass() == null) {
expressionBuilder.setQueryClass(query.getReferenceClass());
}
if (expressionBuilder.getSession() == null) {
expressionBuilder.setSession(query.getSession().getRootSession(null));
}
}
// Computed nested batch attribute expressions, and add them to batch query.
List<Expression> nestedExpressions = extractNestedExpressions(query.getBatchReadAttributeExpressions(), batchQuery.getExpressionBuilder());
batchQuery.getBatchReadAttributeExpressions().addAll(nestedExpressions);
}
batchQuery.setBatchFetchType(batchType);
batchQuery.setBatchFetchSize(query.getBatchFetchPolicy().getSize());
// Allow subclasses to further prepare.
postPrepareNestedBatchQuery(batchQuery, query);
// Set nested fetch group.
if (batchQuery.getDescriptor().hasFetchGroupManager()) {
FetchGroup sourceFetchGroup = query.getExecutionFetchGroup();
if (sourceFetchGroup != null) {
FetchGroup targetFetchGroup = sourceFetchGroup.getGroup(getAttributeName());
if (targetFetchGroup != null) {
batchQuery.setFetchGroup(targetFetchGroup);
}
}
}
if (batchQuery.shouldPrepare()) {
batchQuery.checkPrepare(query.getSession(), query.getTranslationRow());
}
batchQuery.setSession(null);
return batchQuery;
}
Aggregations