use of com.blazebit.persistence.parser.expression.MapKeyExpression in project blaze-persistence by Blazebit.
the class JoinManager method implicitJoin.
private JoinResult implicitJoin(JoinNode current, List<String> resultFields, PathExpression pathExpression, ClauseType fromClause, JoinType joinType, JoinNode currentJoinNode, Set<String> currentlyResolvingAliases, int start, int end, boolean allowParentAliases, boolean joinAllowed, boolean singularJoinAllowed, boolean idRemovable) {
List<PathElementExpression> pathElements = pathExpression.getExpressions();
PathElementExpression elementExpr;
int singleValuedAssociationNameStartIndex = -1;
int singleValuedAssociationNameEndIndex = -1;
for (int i = start; i < end; i++) {
AliasInfo aliasInfo;
elementExpr = pathElements.get(i);
if (elementExpr instanceof ArrayExpression) {
ArrayExpression arrayExpr = (ArrayExpression) elementExpr;
String joinRelationName;
List<String> joinRelationAttributes;
if (!resultFields.isEmpty()) {
resultFields.add(arrayExpr.getBase().toString());
joinRelationAttributes = resultFields;
resultFields = new ArrayList<>();
joinRelationName = StringUtils.join(".", joinRelationAttributes);
} else {
joinRelationName = arrayExpr.getBase().toString();
joinRelationAttributes = Arrays.asList(joinRelationName);
}
current = current == null ? getRootNodeOrFail("Ambiguous join path [", joinRelationName, "] because of multiple root nodes!") : current;
implicitJoinIndex(arrayExpr);
// Find a node by a predicate match
JoinNode matchingNode = findNode(current, joinRelationName, arrayExpr);
if (matchingNode != null) {
current = matchingNode;
} else if (i == 0 && (aliasInfo = aliasManager.getAliasInfoForBottomLevel(joinRelationName)) != null) {
// The first node is allowed to be a join alias
if (aliasInfo instanceof SelectInfo) {
throw new IllegalArgumentException("Illegal reference to the select alias '" + joinRelationName + "'");
}
current = ((JoinAliasInfo) aliasInfo).getJoinNode();
generateAndApplyOnPredicate(current, arrayExpr);
} else {
String joinAlias = getJoinAlias(arrayExpr);
if (arrayExpr.getBase() instanceof PropertyExpression) {
final JoinResult result = createOrUpdateNode(current, joinRelationAttributes, null, joinAlias, joinType, currentJoinNode, true, false, joinAllowed, singularJoinAllowed);
current = result.baseNode;
resultFields = result.addToList(resultFields);
} else {
joinAlias = aliasManager.generateJoinAlias(joinAlias);
Class<?> entityClass = ((EntityLiteral) arrayExpr.getBase()).getValue();
joinOn(null, current.getAlias(), entityClass, joinAlias, JoinType.LEFT, false).end();
current = ((JoinAliasInfo) aliasManager.getAliasInfo(joinAlias)).getJoinNode();
}
generateAndApplyOnPredicate(current, arrayExpr);
}
} else if (elementExpr instanceof TreatExpression) {
if (i != 0 || current != null) {
throw new IllegalArgumentException("A treat expression should be the first element in a path!");
}
TreatExpression treatExpression = (TreatExpression) elementExpr;
boolean fromSubquery = false;
boolean fromSelectAlias = false;
boolean joinRequired = false;
boolean fetch = false;
current = implicitJoinTreatExpression((TreatExpression) elementExpr, joinAllowed, singularJoinAllowed, fromClause, joinType, currentJoinNode, currentlyResolvingAliases, fromSubquery, fromSelectAlias, true, false, fetch, false);
} else if (elementExpr instanceof MapKeyExpression) {
MapKeyExpression mapKeyExpression = (MapKeyExpression) elementExpr;
boolean fromSubquery = false;
boolean fromSelectAlias = false;
boolean joinRequired = true;
boolean fetch = false;
current = joinMapKey(mapKeyExpression, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, joinRequired, fetch, true, true);
} else if (elementExpr instanceof MapValueExpression) {
MapValueExpression mapValueExpression = (MapValueExpression) elementExpr;
boolean fromSubquery = false;
boolean fromSelectAlias = false;
boolean joinRequired = true;
boolean fetch = false;
implicitJoin(mapValueExpression.getPath(), joinAllowed, singularJoinAllowed, true, null, fromClause, currentlyResolvingAliases, fromSubquery, fromSelectAlias, joinRequired, fetch);
current = (JoinNode) mapValueExpression.getPath().getBaseNode();
} else if (pathElements.size() == 1 && (aliasInfo = aliasManager.getAliasInfoForBottomLevel(elementExpr.toString())) != null) {
if (aliasInfo instanceof SelectInfo) {
throw new IllegalArgumentException("Can't dereference a select alias");
} else {
// Join alias usage like in "joinAlias.relationName"
current = ((JoinAliasInfo) aliasInfo).getJoinNode();
}
} else {
String elementExpressionString = elementExpr.toString();
if (current == null) {
// When no base is given, check if the attribute name is an alias
aliasInfo = allowParentAliases ? aliasManager.getAliasInfo(elementExpressionString) : aliasManager.getAliasInfoForBottomLevel(elementExpressionString);
if (aliasInfo instanceof JoinAliasInfo) {
current = ((JoinAliasInfo) aliasInfo).getJoinNode();
// We can only "consider" this path a single valued association id when we are about to "remove" the id part
if (idRemovable && current.getNodeType() instanceof ManagedType<?> && pathElements.size() == i + 2) {
ExtendedManagedType<?> managedType = metamodel.getManagedType(ExtendedManagedType.class, current.getManagedType());
if (contains(managedType.getIdAttributes(), pathElements.get(i + 1))) {
singleValuedAssociationNameStartIndex = 0;
singleValuedAssociationNameEndIndex = 0;
break;
}
}
continue;
} else {
current = getRootNodeOrFail("Ambiguous join path [", elementExpressionString, "] because of multiple root nodes!");
}
}
int pathElementsSize = pathElements.size();
if (joinType != JoinType.INNER && (idRemovable || mainQuery.jpaProvider.supportsSingleValuedAssociationIdExpressions()) && (current.getManagedType().getPersistenceType() != Type.PersistenceType.EMBEDDABLE || current.getValuesLikeAttribute() != null) && i + 1 < pathElementsSize) {
// If the current type is not an embeddable, we check if the path elements access a singular association id
List<PathElementExpression> pathElementExpressions = new ArrayList<>(pathElementsSize - i);
for (int j = i; j < pathElementsSize; j++) {
PathElementExpression pathElementExpression = pathElements.get(j);
if (!(pathElementExpression instanceof PropertyExpression)) {
break;
}
pathElementExpressions.add(pathElementExpression);
}
ExtendedManagedType<?> extendedManagedType = metamodel.getManagedType(ExtendedManagedType.class, current.getManagedType());
// We collect and check if we have only property expressions
if (pathElementExpressions.size() == pathElementsSize - i) {
// Only if all path elements are property expressions, we check if this is single valued association id
PathExpression pathRestExpression = new PathExpression(pathElementExpressions);
String pathRestString = pathRestExpression.toString();
int idx = 0;
ExtendedAttribute<?, ?> extendedAttribute;
if (current.getValuesLikeAttribute() == null) {
extendedAttribute = extendedManagedType.getOwnedSingularAttributes().get(pathRestString);
} else {
extendedAttribute = extendedManagedType.getAttributes().get(pathRestString);
}
if (extendedAttribute != null && !JpaMetamodelUtils.isAssociation(extendedAttribute.getAttribute())) {
ExtendedAttribute<?, ?> associationAttribute = null;
ExtendedAttribute<?, ?> attr;
singleValuedAssociationNameStartIndex = i;
List<String> newResultFields = new ArrayList<>();
for (int j = i; j < end; j++) {
idx = pathRestString.indexOf('.', idx + 1);
if (idx != -1 && JpaMetamodelUtils.isAssociation((attr = extendedManagedType.getAttribute(pathRestString.substring(0, idx))).getAttribute())) {
associationAttribute = attr;
singleValuedAssociationNameEndIndex = j;
}
newResultFields.add(pathElements.get(j).toString());
}
if (singleValuedAssociationNameEndIndex == -1) {
// The expression ends at an association, so this can't be a single valued association id expression
singleValuedAssociationNameStartIndex = -1;
} else if (current.getValueType() == null && mainQuery.jpaProvider.isForeignJoinColumn((EntityType<?>) current.getManagedType(), new PathExpression(pathElements.subList(singleValuedAssociationNameStartIndex, singleValuedAssociationNameEndIndex + 1)).toString()) || current.getValueType() != null && mainQuery.jpaProvider.isForeignJoinColumn(current.getValueType(), current.getValuesLikeAttribute() + "." + new PathExpression(pathElements.subList(singleValuedAssociationNameStartIndex, singleValuedAssociationNameEndIndex + 1)).toString())) {
// If the column is "foreign", we can't do any optimizations
singleValuedAssociationNameStartIndex = -1;
} else if (!mainQuery.jpaProvider.supportsSingleValuedAssociationNaturalIdExpressions() && !contains(metamodel.getManagedType(ExtendedManagedType.class, associationAttribute.getElementClass()), new PathExpression(pathElements.subList(singleValuedAssociationNameEndIndex + 1, pathElementsSize)))) {
// If the jpa provider doesn't support any optimizations, we are done
singleValuedAssociationNameStartIndex = -1;
} else {
resultFields.addAll(newResultFields);
break;
}
}
}
}
if (resultFields.isEmpty()) {
final JoinResult result = implicitJoinSingle(current, elementExpressionString, null, joinType, currentJoinNode, allowParentAliases, joinAllowed, singularJoinAllowed);
if (current != result.baseNode) {
current = result.baseNode;
}
resultFields = result.addToList(resultFields);
} else {
resultFields.add(elementExpressionString);
JoinResult currentResult = createOrUpdateNode(current, resultFields, null, null, joinType, currentJoinNode, true, true, joinAllowed, singularJoinAllowed);
current = currentResult.baseNode;
if (!currentResult.hasField()) {
resultFields.clear();
}
}
}
}
if (resultFields.isEmpty()) {
return new JoinResult(current, null, current == null ? null : current.getNodeType(), singleValuedAssociationNameStartIndex, singleValuedAssociationNameEndIndex);
} else {
List<PathElementExpression> pathElementExpressions = new ArrayList<>(resultFields.size());
for (int i = 0; i < resultFields.size(); i++) {
pathElementExpressions.add(new PropertyExpression(resultFields.get(i)));
}
Expression expression = new PathExpression(pathElementExpressions);
Type<?> type = JpaUtils.getAttributeForJoining(metamodel, current.getNodeType(), expression, null).getAttributeType();
return new JoinResult(current, resultFields, type, singleValuedAssociationNameStartIndex, singleValuedAssociationNameEndIndex);
}
}
use of com.blazebit.persistence.parser.expression.MapKeyExpression in project blaze-persistence by Blazebit.
the class JoinManager method join.
JoinNode join(Expression expr, String alias, JoinType type, boolean fetch, boolean defaultJoin, String deReferenceFunction) {
PathElementExpression elementExpr;
String treatType = null;
JoinResult result;
JoinNode current;
if (type == JoinType.FULL) {
hasFullJoin = true;
}
if (expr instanceof PathExpression) {
PathExpression pathExpression = (PathExpression) expr;
if (isExternal(pathExpression) || isJoinableSelectAlias(pathExpression, false, false)) {
throw new IllegalArgumentException("No external path or select alias allowed in join path");
}
List<PathElementExpression> pathElements = pathExpression.getExpressions();
elementExpr = pathElements.get(pathElements.size() - 1);
result = implicitJoin(null, pathExpression, null, null, null, new HashSet<String>(), 0, pathElements.size() - 1, false, true, true, false);
current = result.baseNode;
} else if (expr instanceof QualifiedExpression) {
elementExpr = (PathElementExpression) expr;
result = null;
current = null;
} else if (expr instanceof TreatExpression) {
TreatExpression treatExpression = (TreatExpression) expr;
if (isExternal(treatExpression)) {
throw new IllegalArgumentException("No external path or select alias allowed in join path");
}
Expression expression = treatExpression.getExpression();
if (expression instanceof PathExpression) {
PathExpression pathExpression = (PathExpression) expression;
List<PathElementExpression> pathElements = pathExpression.getExpressions();
elementExpr = pathElements.get(pathElements.size() - 1);
result = implicitJoin(null, pathExpression, null, null, null, new HashSet<String>(), 0, pathElements.size() - 1, false, true, true, false);
current = result.baseNode;
treatType = treatExpression.getType();
} else {
throw new IllegalArgumentException("Unexpected expression type[" + expression.getClass().getSimpleName() + "] in treat expression: " + treatExpression);
}
} else {
throw new IllegalArgumentException("Join path [" + expr + "] is not a path");
}
if (elementExpr instanceof ArrayExpression) {
ArrayExpression arrayExpr = (ArrayExpression) elementExpr;
implicitJoinIndex(arrayExpr);
if (arrayExpr.getBase() instanceof PropertyExpression) {
List<String> resultFields = result.addToList(new ArrayList<String>());
current = current == null ? getRootNodeOrFail("Could not join path [", expr, "] because it did not use an absolute path but multiple root nodes are available!") : current;
resultFields.add(arrayExpr.getBase().toString());
result = createOrUpdateNode(current, resultFields, treatType, alias, type, null, false, defaultJoin, true, true);
} else {
Class<?> entityClass = ((EntityLiteral) arrayExpr.getBase()).getValue();
joinOn(null, rootNodes.get(0).getAlias(), entityClass, alias, JoinType.LEFT, false).end();
result = new JoinResult(((JoinAliasInfo) aliasManager.getAliasInfo(alias)).getJoinNode());
}
generateAndApplyOnPredicate(result.baseNode, arrayExpr);
} else if (elementExpr instanceof MapKeyExpression) {
MapKeyExpression mapKeyExpression = (MapKeyExpression) elementExpr;
boolean fromSubquery = false;
boolean fromSelectAlias = false;
boolean joinRequired = true;
current = joinMapKey(mapKeyExpression, alias, null, new HashSet<String>(), fromSubquery, fromSelectAlias, joinRequired, fetch, false, defaultJoin);
result = new JoinResult(current);
} else {
List<String> joinRelationAttributes = result.addToList(new ArrayList<String>());
joinRelationAttributes.add(elementExpr.toString());
current = current == null ? getRootNodeOrFail("Could not join path [", expr, "] because it did not use an absolute path but multiple root nodes are available!") : current;
result = createOrUpdateNode(current, joinRelationAttributes, treatType, alias, type, null, false, defaultJoin, true, true);
}
result.baseNode.setDeReferenceFunction(deReferenceFunction);
if (fetch) {
fetchPath(result.baseNode);
}
return result.baseNode;
}
use of com.blazebit.persistence.parser.expression.MapKeyExpression in project blaze-persistence by Blazebit.
the class JoinManager method getArrayExpressionPredicate.
private Predicate getArrayExpressionPredicate(JoinNode joinNode, ArrayExpression arrayExpr) {
if (arrayExpr.getIndex() instanceof Predicate) {
return (Predicate) arrayExpr.getIndex();
} else {
PathExpression keyPath = new PathExpression(new ArrayList<PathElementExpression>(), true);
keyPath.getExpressions().add(new PropertyExpression(joinNode.getAliasInfo().getAlias()));
keyPath.setPathReference(new SimplePathReference(joinNode, null, joinNode.getNodeType()));
Attribute<?, ?> arrayBaseAttribute = joinNode.getParentTreeNode().getAttribute();
Expression keyExpression;
if (arrayBaseAttribute instanceof ListAttribute<?, ?>) {
keyExpression = new ListIndexExpression(keyPath);
} else {
keyExpression = new MapKeyExpression(keyPath);
}
return new EqPredicate(keyExpression, arrayExpr.getIndex());
}
}
use of com.blazebit.persistence.parser.expression.MapKeyExpression in project blaze-persistence by Blazebit.
the class JoinNode method createExpression.
public Expression createExpression(String field, boolean asPath) {
List<PathElementExpression> pathElements = new ArrayList<>();
if (qualificationExpression != null) {
List<PathElementExpression> pathElementExpressions = new ArrayList<>(1);
pathElementExpressions.add(new PropertyExpression(parent.getAlias()));
PathExpression path = new PathExpression(pathElementExpressions);
if ("KEY".equalsIgnoreCase(qualificationExpression)) {
pathElements.add(new MapKeyExpression(path));
} else if ("INDEX".equalsIgnoreCase(qualificationExpression)) {
pathElements.add(new ListIndexExpression(path));
} else if ("ENTRY".equalsIgnoreCase(qualificationExpression)) {
pathElements.add(new MapEntryExpression(path));
}
} else {
pathElements.add(new PropertyExpression(aliasInfo.getAlias()));
}
if (field != null) {
for (String fieldPart : field.split("\\.")) {
pathElements.add(new PropertyExpression(fieldPart));
}
}
if (!asPath && valuesTypeName != null) {
return new FunctionExpression("FUNCTION", Arrays.asList(new StringLiteral("TREAT_" + valuesTypeName.toUpperCase()), new PathExpression(pathElements)));
} else {
return new PathExpression(pathElements);
}
}
use of com.blazebit.persistence.parser.expression.MapKeyExpression in project blaze-persistence by Blazebit.
the class AbstractAttribute method checkAttribute.
public void checkAttribute(ManagedType<?> managedType, MetamodelBuildingContext context) {
Class<?> expressionType = getJavaType();
Class<?> keyType = null;
Class<?> elementType = null;
ManagedType<?> elementManagedType;
javax.persistence.metamodel.Attribute<?, ?> elementAttribute;
if (possibleTargetTypes.size() != 1) {
if (getElementType() instanceof ManagedViewType<?>) {
elementManagedType = context.getEntityMetamodel().getManagedType(((ManagedViewType<?>) getElementType()).getEntityClass());
} else {
elementManagedType = context.getEntityMetamodel().getManagedType(getElementType().getJavaType());
}
elementAttribute = null;
} else {
elementManagedType = context.getEntityMetamodel().getManagedType(possibleTargetTypes.get(0).getLeafBaseValueClass());
elementAttribute = possibleTargetTypes.get(0).getLeafMethod();
}
ScalarTargetResolvingExpressionVisitor visitor = new ScalarTargetResolvingExpressionVisitor(elementManagedType, elementAttribute, context.getEntityMetamodel(), context.getJpqlFunctions(), declaringType.getEntityViewRootTypes());
if (fetches.length != 0) {
if (context.getEntityMetamodel().getManagedType(getElementType().getJavaType()) == null) {
context.addError("Specifying fetches for non-entity attribute type [" + Arrays.toString(fetches) + "] at the " + getLocation() + " is not allowed!");
} else {
for (int i = 0; i < fetches.length; i++) {
final String fetch = fetches[i];
final String errorLocation;
if (fetches.length == 1) {
errorLocation = "the fetch expression";
} else {
errorLocation = "the " + (i + 1) + ". fetch expression";
}
visitor.clear();
try {
// Validate the fetch expression parses
context.getExpressionFactory().createPathExpression(fetch).accept(visitor);
} catch (SyntaxErrorException ex) {
try {
context.getExpressionFactory().createSimpleExpression(fetch, false, false, true);
// The used expression is not usable for fetches
context.addError("Invalid fetch expression '" + fetch + "' of the " + getLocation() + ". Simplify the fetch expression to a simple path expression. Encountered error: " + ex.getMessage());
} catch (SyntaxErrorException ex2) {
// This is a real syntax error
context.addError("Syntax error in " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
}
} catch (IllegalArgumentException ex) {
context.addError("An error occurred while trying to resolve the " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
}
}
}
}
if (limitExpression != null) {
try {
Expression inItemExpression = context.getTypeValidationExpressionFactory().createInItemExpression(limitExpression);
if (!(inItemExpression instanceof ParameterExpression) && !(inItemExpression instanceof NumericLiteral) || inItemExpression instanceof NumericLiteral && ((NumericLiteral) inItemExpression).getNumericType() != NumericType.INTEGER) {
context.addError("Syntax error in the limit expression '" + limitExpression + "' of the " + getLocation() + ": The expression must be a integer literal or a parameter expression");
}
} catch (SyntaxErrorException ex) {
context.addError("Syntax error in the limit expression '" + limitExpression + "' of the " + getLocation() + ": " + ex.getMessage());
} catch (IllegalArgumentException ex) {
context.addError("An error occurred while trying to resolve the limit expression '" + limitExpression + "' of the " + getLocation() + ": " + ex.getMessage());
}
try {
Expression inItemExpression = context.getTypeValidationExpressionFactory().createInItemExpression(offsetExpression);
if (!(inItemExpression instanceof ParameterExpression) && !(inItemExpression instanceof NumericLiteral) || inItemExpression instanceof NumericLiteral && ((NumericLiteral) inItemExpression).getNumericType() != NumericType.INTEGER) {
context.addError("Syntax error in the offset expression '" + offsetExpression + "' of the " + getLocation() + ": The expression must be a integer literal or a parameter expression");
}
} catch (SyntaxErrorException ex) {
context.addError("Syntax error in the offset expression '" + offsetExpression + "' of the " + getLocation() + ": " + ex.getMessage());
} catch (IllegalArgumentException ex) {
context.addError("An error occurred while trying to resolve the offset expression '" + offsetExpression + "' of the " + getLocation() + ": " + ex.getMessage());
}
for (int i = 0; i < orderByItems.size(); i++) {
OrderByItem orderByItem = orderByItems.get(i);
String expression = orderByItem.getExpression();
try {
visitor.clear();
context.getTypeValidationExpressionFactory().createSimpleExpression(expression, false, false, true).accept(visitor);
} catch (SyntaxErrorException ex) {
context.addError("Syntax error in the " + (i + 1) + "th order by expression '" + expression + "' of the " + getLocation() + ": " + ex.getMessage());
} catch (IllegalArgumentException ex) {
context.addError("An error occurred while trying to resolve the " + (i + 1) + "th order by expression '" + expression + "' of the " + getLocation() + ": " + ex.getMessage());
}
}
}
if (fetchStrategy == FetchStrategy.MULTISET) {
if (getElementType() instanceof ManagedViewTypeImplementor<?> && ((ManagedViewTypeImplementor<?>) getElementType()).hasJpaManagedAttributes()) {
context.addError("Using the MULTISET fetch strategy is not allowed when the subview contains attributes with entity types. MULTISET at the " + getLocation() + " is not allowed!");
} else if (getElementType() instanceof BasicTypeImpl<?> && ((BasicTypeImpl<?>) getElementType()).isJpaManaged()) {
context.addError("Using the MULTISET fetch strategy is not allowed with entity types. MULTISET at the " + getLocation() + " is not allowed!");
}
}
Expression indexExpression = null;
if (isCollection()) {
elementType = getElementType().getJavaType();
if (!isUpdatable()) {
// Updatable collection attributes are specially handled in the type compatibility check
if (isIndexed()) {
if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
expressionType = Collection.class;
keyType = getKeyType().getJavaType();
} else {
expressionType = Collection.class;
keyType = Integer.class;
}
} else {
// We can assign e.g. a Set to a List, so let's use the common supertype
expressionType = Collection.class;
}
}
if (isIndexed()) {
if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
indexExpression = getKeyMappingExpression();
String[] keyFetches = getKeyFetches();
if (keyFetches.length != 0) {
ManagedType<?> managedKeyType = context.getEntityMetamodel().getManagedType(getKeyType().getJavaType());
if (managedKeyType == null) {
context.addError("Specifying key fetches for non-entity attribute key type [" + Arrays.toString(keyFetches) + "] at the " + getLocation() + " is not allowed!");
} else {
ScalarTargetResolvingExpressionVisitor keyVisitor = new ScalarTargetResolvingExpressionVisitor(managedKeyType, context.getEntityMetamodel(), context.getJpqlFunctions(), declaringType.getEntityViewRootTypes());
for (int i = 0; i < keyFetches.length; i++) {
final String fetch = keyFetches[i];
final String errorLocation;
if (keyFetches.length == 1) {
errorLocation = "the key fetch expression";
} else {
errorLocation = "the " + (i + 1) + ". key fetch expression";
}
keyVisitor.clear();
try {
// Validate the fetch expression parses
context.getExpressionFactory().createPathExpression(fetch).accept(keyVisitor);
} catch (SyntaxErrorException ex) {
try {
context.getExpressionFactory().createSimpleExpression(fetch, false, false, true);
// The used expression is not usable for fetches
context.addError("Invalid key fetch expression '" + fetch + "' of the " + getLocation() + ". Simplify the key fetch expression to a simple path expression. Encountered error: " + ex.getMessage());
} catch (SyntaxErrorException ex2) {
// This is a real syntax error
context.addError("Syntax error in " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
}
} catch (IllegalArgumentException ex) {
context.addError("An error occurred while trying to resolve the " + errorLocation + " '" + fetch + "' of the " + getLocation() + ": " + ex.getMessage());
}
}
}
}
} else {
indexExpression = getMappingIndexExpression();
}
}
}
if (isSubview()) {
ManagedViewTypeImplementor<?> subviewType = (ManagedViewTypeImplementor<?>) getElementType();
if (isCollection()) {
elementType = subviewType.getEntityClass();
} else {
expressionType = subviewType.getEntityClass();
}
} else {
// If we determined, that the java type is a basic type, let's double check if the user didn't do something wrong
Class<?> elementJavaType = getElementType().getJavaType();
if ((elementJavaType.getModifiers() & Modifier.ABSTRACT) != 0) {
// If the element type has an entity view annotation, although it is considered basic, we throw an error as this means, the view was probably not registered
if (!isQueryParameter() && AnnotationUtils.findAnnotation(elementJavaType, EntityView.class) != null && getElementType().getConvertedType() == null) {
context.addError("The element type '" + elementJavaType.getName() + "' is considered basic although the class is annotated with @EntityView. Add a type converter or add the java class to the entity view configuration! Problematic attribute " + getLocation());
}
}
}
if (isKeySubview()) {
keyType = ((ManagedViewTypeImplementor<?>) getKeyType()).getEntityClass();
}
if (keyType != null) {
validateTypesCompatible(possibleIndexTargetTypes, keyType, null, isUpdatable(), true, context, ExpressionLocation.MAPPING_INDEX, getLocation());
}
if (isCorrelated()) {
// Validate that resolving "correlationBasis" on "managedType" is valid
validateTypesCompatible(managedType, correlationBasisExpression, Object.class, null, false, true, declaringType.getEntityViewRootTypes(), context, ExpressionLocation.CORRELATION_BASIS, getLocation());
if (correlated != null) {
// Validate that resolving "correlationResult" on "correlated" is compatible with "expressionType" and "elementType"
validateTypesCompatible(possibleTargetTypes, expressionType, elementType, false, !isCollection(), context, ExpressionLocation.CORRELATION_RESULT, getLocation());
Predicate correlationPredicate = getCorrelationPredicate();
if (correlationPredicate != null) {
ExpressionFactory ef = context.getTypeValidationExpressionFactory();
// First we need to prefix the correlation basis expression with an alias because we use that in the predicate
PrefixingQueryGenerator prefixingQueryGenerator = new PrefixingQueryGenerator(ef, correlationKeyAlias, null, null, declaringType.getEntityViewRootTypes().keySet(), false, false);
prefixingQueryGenerator.setQueryBuffer(new StringBuilder());
correlationBasisExpression.accept(prefixingQueryGenerator);
// Next we replace the plain alias usage with the prefixed correlation basis expression
AliasReplacementVisitor aliasReplacementVisitor = new AliasReplacementVisitor(ef.createSimpleExpression(prefixingQueryGenerator.getQueryBuffer().toString()), correlationKeyAlias);
correlationPredicate = correlationPredicate.copy(ExpressionCopyContext.EMPTY);
correlationPredicate.accept(aliasReplacementVisitor);
// Finally we validate that the expression
try {
Map<String, javax.persistence.metamodel.Type<?>> rootTypes = new HashMap<>(declaringType.getEntityViewRootTypes());
rootTypes.put(correlationKeyAlias, managedType);
ScalarTargetResolvingExpressionVisitor correlationVisitor = new ScalarTargetResolvingExpressionVisitor(correlated, context.getEntityMetamodel(), context.getJpqlFunctions(), rootTypes);
correlationPredicate.accept(correlationVisitor);
} catch (SyntaxErrorException ex) {
context.addError("Syntax error in the condition expression '" + correlationPredicate + "' of the " + getLocation() + ": " + ex.getMessage());
} catch (IllegalArgumentException ex) {
context.addError("An error occurred while trying to resolve the condition expression '" + correlationPredicate + "' of the " + getLocation() + ": " + ex.getMessage());
}
}
}
} else if (isSubquery()) {
if (subqueryExpression != null && !subqueryExpression.isEmpty()) {
// If a converter is applied, we already know that there was a type match with the underlying type
if (getElementType().getConvertedType() == null) {
validateTypesCompatible(possibleTargetTypes, expressionType, elementType, false, !isCollection(), context, ExpressionLocation.SUBQUERY_EXPRESSION, getLocation());
}
}
} else if (!isQueryParameter()) {
// Forcing singular via @MappingSingular
if (!isCollection() && (Collection.class.isAssignableFrom(expressionType) || Map.class.isAssignableFrom(expressionType))) {
Class<?>[] typeArguments = getTypeArguments();
elementType = typeArguments[typeArguments.length - 1];
}
// If a converter is applied, we already know that there was a type match with the underlying type
if (getElementType().getConvertedType() == null) {
// Validate that resolving "mapping" on "managedType" is compatible with "expressionType" and "elementType"
validateTypesCompatible(possibleTargetTypes, expressionType, elementType, isUpdatable(), !isCollection(), context, ExpressionLocation.MAPPING, getLocation());
}
if (isMutable() && (declaringType.isUpdatable() || declaringType.isCreatable())) {
UpdatableExpressionVisitor updatableVisitor = new UpdatableExpressionVisitor(context.getEntityMetamodel(), managedType.getJavaType(), isUpdatable(), declaringType.getEntityViewRootTypes());
try {
// NOTE: Not supporting "this" here because it doesn't make sense to have an updatable mapping that refers to this
// The only thing that might be interesting is supporting "this" when we support cascading as properties could be nested
// But not sure yet if the embeddable attributes would then be modeled as "updatable".
// I guess these attributes are not "updatable" but that probably depends on the decision regarding collections as they have a similar problem
// A collection itself might not be "updatable" but it's elements could be. This is roughly the same problem
mappingExpression.accept(updatableVisitor);
Map<javax.persistence.metamodel.Attribute<?, ?>, javax.persistence.metamodel.Type<?>> possibleTargets = updatableVisitor.getPossibleTargets();
if (possibleTargets.size() > 1) {
context.addError("Multiple possible target type for the mapping in the " + getLocation() + ": " + possibleTargets);
}
// TODO: maybe allow to override this per-attribute?
if (isDisallowOwnedUpdatableSubview()) {
for (Type<?> updateCascadeAllowedSubtype : getUpdateCascadeAllowedSubtypes()) {
ManagedViewType<?> managedViewType = (ManagedViewType<?>) updateCascadeAllowedSubtype;
if (managedViewType.isUpdatable()) {
context.addError("Invalid use of @UpdatableEntityView type '" + managedViewType.getJavaType().getName() + "' for the " + getLocation() + ". Consider using a read-only view type instead or use @AllowUpdatableEntityViews! " + "For further information on this topic, please consult the documentation https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#updatable-mappings-subview");
}
}
}
} catch (IllegalArgumentException ex) {
context.addError("There is an error for the " + getLocation() + ": " + ex.getMessage());
}
if (isUpdatable()) {
if (isCollection() && getElementCollectionType() != null) {
context.addError("The use of a multi-collection i.e. List<Collection<?>> or Map<?, Collection<?>> at the " + getLocation() + " is unsupported for updatable collections!");
}
}
if ((isUpdatable() || isKeySubview() && ((ManagedViewTypeImplementor<?>) getKeyType()).isUpdatable()) && indexExpression != null) {
boolean invalid;
if (getCollectionType() == PluralAttribute.CollectionType.MAP) {
invalid = !(indexExpression instanceof MapKeyExpression) || !"this".equals(((MapKeyExpression) indexExpression).getPath().getPath());
} else {
invalid = !(indexExpression instanceof ListIndexExpression) || !"this".equals(((ListIndexExpression) indexExpression).getPath().getPath());
}
if (invalid) {
context.addError("The @MappingIndex at the " + getLocation() + " is a complex mapping and can thus not be updatable!");
}
}
}
}
}
Aggregations