use of com.blazebit.persistence.spi.JpaMetamodelAccessor in project blaze-persistence by Blazebit.
the class JpaUtils method expandBindings.
public static void expandBindings(Map<String, Integer> bindingMap, Map<String, String> columnBindingMap, Map<String, ExtendedAttribute<?, ?>> attributeEntries, ClauseType clause, AbstractCommonQueryBuilder<?, ?, ?, ?, ?> queryBuilder, String keyFunctionExpression, boolean enableElementCollectionIdCutoff) {
SelectManager<?> selectManager = queryBuilder.selectManager;
JoinManager joinManager = queryBuilder.joinManager;
ParameterManager parameterManager = queryBuilder.parameterManager;
JpaProvider jpaProvider = queryBuilder.mainQuery.jpaProvider;
EntityMetamodelImpl metamodel = queryBuilder.mainQuery.metamodel;
boolean requiresNullCast = queryBuilder.mainQuery.dbmsDialect.requiresNullCast();
boolean needsCastParameters = queryBuilder.mainQuery.dbmsDialect.needsCastParameters();
JpaMetamodelAccessor jpaMetamodelAccessor = jpaProvider.getJpaMetamodelAccessor();
boolean needsElementCollectionIdCutoff = enableElementCollectionIdCutoff && jpaProvider.needsElementCollectionIdCutoff();
final Queue<String> attributeQueue = new ArrayDeque<>(bindingMap.keySet());
while (!attributeQueue.isEmpty()) {
final String attributeName = attributeQueue.remove();
Integer tupleIndex = bindingMap.get(attributeName);
Class<?> elementType;
String columnType;
boolean splitExpression;
ExtendedAttribute<?, ?> attributeEntry = attributeEntries.get(attributeName);
if (attributeEntry == null) {
if (!attributeName.equalsIgnoreCase(keyFunctionExpression)) {
continue;
}
String realAttributeName = attributeName.substring(attributeName.indexOf('(') + 1, attributeName.length() - 1);
attributeEntry = attributeEntries.get(realAttributeName);
if (attributeEntry.getAttribute() instanceof ListAttribute<?, ?>) {
elementType = Integer.class;
columnType = queryBuilder.mainQuery.dbmsDialect.getSqlType(Integer.class);
} else {
MapAttribute<?, ?, ?> mapAttribute = (MapAttribute<?, ?, ?>) attributeEntry.getAttribute();
elementType = mapAttribute.getKeyJavaType();
columnType = attributeEntry.getJoinTable() != null && attributeEntry.getJoinTable().getKeyColumnTypes() != null && attributeEntry.getJoinTable().getKeyColumnTypes().size() == 1 ? attributeEntry.getJoinTable().getKeyColumnTypes().values().iterator().next() : null;
}
splitExpression = false;
} else {
elementType = attributeEntry.getElementClass();
columnType = attributeEntry.getColumnTypes().length == 0 ? null : attributeEntry.getColumnTypes()[0];
final List<Attribute<?, ?>> attributePath = attributeEntry.getAttributePath();
final Attribute<?, ?> lastAttribute = attributePath.get(attributePath.size() - 1);
splitExpression = lastAttribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED;
if (!splitExpression) {
if ((clause != ClauseType.SET || jpaProvider.supportsUpdateSetAssociationId()) && jpaMetamodelAccessor.isJoinable(lastAttribute) && !isBasicElementType(lastAttribute)) {
splitExpression = true;
if (needsElementCollectionIdCutoff) {
OUTER: for (int i = 0; i < attributePath.size() - 1; i++) {
Attribute<?, ?> attribute = attributePath.get(i);
if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.ELEMENT_COLLECTION) {
// This is a special case, when an embeddable is between an element collection and the association, we still need to split the expression
for (int j = i + 1; j < attributePath.size() - 1; j++) {
attribute = attributePath.get(j);
if (attribute.getPersistentAttributeType() == Attribute.PersistentAttributeType.EMBEDDED) {
break OUTER;
}
}
splitExpression = false;
break;
}
}
}
}
}
}
SelectInfo selectInfo = selectManager.getSelectInfos().get(tupleIndex);
final Expression selectExpression = selectInfo.getExpression();
if (splitExpression) {
// TODO: Maybe also allow Treat, Case-When, Array?
if (selectExpression instanceof NullExpression) {
final Collection<String> embeddedPropertyNames = getEmbeddedPropertyPaths(attributeEntries, attributeName, needsElementCollectionIdCutoff, false);
if (embeddedPropertyNames.size() > 0) {
selectManager.getSelectInfos().remove(tupleIndex.intValue());
bindingMap.remove(attributeName);
// We are going to insert the expanded attributes as new select items and shift existing ones
int delta = embeddedPropertyNames.size() - 1;
if (delta > 0) {
for (Map.Entry<String, Integer> entry : bindingMap.entrySet()) {
if (entry.getValue() > tupleIndex) {
entry.setValue(entry.getValue() + delta);
}
}
}
int offset = 0;
for (String embeddedPropertyName : embeddedPropertyNames) {
String nestedAttributePath = attributeName + "." + embeddedPropertyName;
ExtendedAttribute<?, ?> nestedAttributeEntry = attributeEntries.get(nestedAttributePath);
// Process the nested attribute path recursively
attributeQueue.add(nestedAttributePath);
// Replace this binding in the binding map, additional selects need an updated index
bindingMap.put(nestedAttributePath, tupleIndex + offset);
selectManager.select(offset == 0 ? selectExpression : selectExpression.copy(ExpressionCopyContext.EMPTY), null, tupleIndex + offset);
if (columnBindingMap != null) {
for (String column : nestedAttributeEntry.getColumnNames()) {
columnBindingMap.put(column, nestedAttributePath);
}
}
offset++;
}
}
} else if (selectExpression instanceof PathExpression) {
boolean firstBinding = true;
final Collection<String> embeddedPropertyNames = getEmbeddedPropertyPaths(attributeEntries, attributeName, needsElementCollectionIdCutoff, false);
PathExpression baseExpression = embeddedPropertyNames.size() > 1 ? ((PathExpression) selectExpression).copy(ExpressionCopyContext.EMPTY) : ((PathExpression) selectExpression);
joinManager.implicitJoin(baseExpression, true, true, true, null, ClauseType.SELECT, new HashSet<String>(), false, false, false, false);
if (elementType != baseExpression.getPathReference().getType().getJavaType()) {
throw new IllegalStateException("An association should be bound to its association type and not its identifier type");
}
if (embeddedPropertyNames.size() > 0) {
bindingMap.remove(attributeName);
// We are going to insert the expanded attributes as new select items and shift existing ones
int delta = embeddedPropertyNames.size() - 1;
if (delta > 0) {
for (Map.Entry<String, Integer> entry : bindingMap.entrySet()) {
if (entry.getValue() > tupleIndex) {
entry.setValue(entry.getValue() + delta);
}
}
}
int offset = 0;
for (String embeddedPropertyName : embeddedPropertyNames) {
PathExpression pathExpression = firstBinding ? ((PathExpression) selectExpression) : baseExpression.copy(ExpressionCopyContext.EMPTY);
for (String propertyNamePart : embeddedPropertyName.split("\\.")) {
pathExpression.getExpressions().add(new PropertyExpression(propertyNamePart));
}
String nestedAttributePath = attributeName + "." + embeddedPropertyName;
ExtendedAttribute<?, ?> nestedAttributeEntry = attributeEntries.get(nestedAttributePath);
// Process the nested attribute path recursively
attributeQueue.add(nestedAttributePath);
// Replace this binding in the binding map, additional selects need an updated index
bindingMap.put(nestedAttributePath, firstBinding ? tupleIndex : tupleIndex + offset);
if (!firstBinding) {
selectManager.select(pathExpression, null, tupleIndex + offset);
} else {
firstBinding = false;
}
if (columnBindingMap != null) {
for (String column : nestedAttributeEntry.getColumnNames()) {
columnBindingMap.put(column, nestedAttributePath);
}
}
offset++;
}
}
} else if (selectExpression instanceof ParameterExpression) {
final Collection<String> embeddedPropertyNames = getEmbeddedPropertyPaths(attributeEntries, attributeName, jpaProvider.needsElementCollectionIdCutoff(), false);
if (embeddedPropertyNames.size() > 0) {
ParameterExpression parameterExpression = (ParameterExpression) selectExpression;
String parameterName = parameterExpression.getName();
Map<String, List<String>> parameterAccessPaths = new HashMap<>(embeddedPropertyNames.size());
ParameterValueTransformer tranformer = parameterManager.getParameter(parameterName).getTransformer();
if (tranformer instanceof SplittingParameterTransformer) {
for (String name : ((SplittingParameterTransformer) tranformer).getParameterNames()) {
parameterManager.unregisterParameterName(name, clause, queryBuilder);
}
}
selectManager.getSelectInfos().remove(tupleIndex.intValue());
bindingMap.remove(attributeName);
// We are going to insert the expanded attributes as new select items and shift existing ones
int delta = embeddedPropertyNames.size() - 1;
if (delta > 0) {
for (Map.Entry<String, Integer> entry : bindingMap.entrySet()) {
if (entry.getValue() > tupleIndex) {
entry.setValue(entry.getValue() + delta);
}
}
}
int offset = 0;
for (String embeddedPropertyName : embeddedPropertyNames) {
String subParamName = "_" + parameterName + "_" + embeddedPropertyName.replace('.', '_');
parameterManager.registerParameterName(subParamName, false, clause, queryBuilder);
parameterAccessPaths.put(subParamName, Arrays.asList(embeddedPropertyName.split("\\.")));
String nestedAttributePath = attributeName + "." + embeddedPropertyName;
ExtendedAttribute<?, ?> nestedAttributeEntry = attributeEntries.get(nestedAttributePath);
// Process the nested attribute path recursively
attributeQueue.add(nestedAttributePath);
// Replace this binding in the binding map, additional selects need an updated index
bindingMap.put(nestedAttributePath, tupleIndex + offset);
selectManager.select(new ParameterExpression(subParamName), null, tupleIndex + offset);
if (columnBindingMap != null) {
for (String column : nestedAttributeEntry.getColumnNames()) {
columnBindingMap.put(column, nestedAttributePath);
}
}
offset++;
}
parameterManager.getParameter(parameterName).setTransformer(new SplittingParameterTransformer(parameterManager, metamodel, elementType, parameterAccessPaths));
}
} else {
throw new IllegalArgumentException("Illegal expression '" + selectExpression.toString() + "' for binding relation '" + attributeName + "'!");
}
} else if (requiresNullCast && selectExpression instanceof NullExpression) {
if (BasicCastTypes.TYPES.contains(elementType) && queryBuilder.statementType != DbmsStatementType.INSERT) {
// We also need a cast for parameter expressions except in the SET clause
List<Expression> arguments = new ArrayList<>(2);
arguments.add(selectExpression);
if (columnType != null) {
arguments.add(new StringLiteral(columnType));
}
selectInfo.set(new FunctionExpression("CAST_" + elementType.getSimpleName(), arguments, selectExpression));
} else {
final EntityMetamodelImpl.AttributeExample attributeExample = metamodel.getBasicTypeExampleAttributes().get(elementType);
if (attributeExample != null) {
List<Expression> arguments = new ArrayList<>(2);
arguments.add(new SubqueryExpression(new Subquery() {
@Override
public String getQueryString() {
return attributeExample.getExampleJpql() + selectExpression;
}
}));
if (queryBuilder.statementType != DbmsStatementType.INSERT && needsCastParameters) {
arguments.add(new StringLiteral(attributeExample.getAttribute().getColumnTypes()[0]));
}
selectInfo.set(new FunctionExpression(NullfnFunction.FUNCTION_NAME, arguments, selectExpression));
}
}
} else if (selectExpression instanceof ParameterExpression && clause != ClauseType.SET) {
if (BasicCastTypes.TYPES.contains(elementType) && queryBuilder.statementType != DbmsStatementType.INSERT) {
// We also need a cast for parameter expressions except in the SET clause
List<Expression> arguments = new ArrayList<>(2);
arguments.add(selectExpression);
if (columnType != null) {
arguments.add(new StringLiteral(columnType));
}
selectInfo.set(new FunctionExpression("CAST_" + elementType.getSimpleName(), arguments, selectExpression));
} else {
final EntityMetamodelImpl.AttributeExample attributeExample = metamodel.getBasicTypeExampleAttributes().get(elementType);
if (attributeExample != null) {
List<Expression> arguments = new ArrayList<>(2);
arguments.add(new SubqueryExpression(new Subquery() {
@Override
public String getQueryString() {
return attributeExample.getExampleJpql() + selectExpression;
}
}));
if (queryBuilder.statementType != DbmsStatementType.INSERT && needsCastParameters) {
arguments.add(new StringLiteral(attributeExample.getAttribute().getColumnTypes()[0]));
}
selectInfo.set(new FunctionExpression(ParamFunction.FUNCTION_NAME, arguments, selectExpression));
}
}
}
}
}
use of com.blazebit.persistence.spi.JpaMetamodelAccessor in project blaze-persistence by Blazebit.
the class AbstractInsertCollectionCriteriaBuilder method getForeignKeyParticipatingQueries.
protected Collection<Query> getForeignKeyParticipatingQueries() {
Map<String, Query> map = null;
JpaMetamodelAccessor jpaMetamodelAccessor = mainQuery.jpaProvider.getJpaMetamodelAccessor();
for (String attributeName : bindingMap.keySet()) {
ExtendedAttribute<?, ?> attribute = collectionAttributeEntries.get(attributeName);
if (attribute == null) {
continue;
}
for (Attribute<?, ?> attributePart : attribute.getAttributePath()) {
if (attributePart instanceof SingularAttribute<?, ?>) {
SingularAttribute<?, ?> singularAttribute = (SingularAttribute<?, ?>) attributePart;
if (map == null) {
map = new HashMap<>();
}
if (singularAttribute.getType() instanceof EntityType<?>) {
String entityName = ((EntityType<?>) singularAttribute.getType()).getName();
if (!map.containsKey(entityName)) {
map.put(entityName, em.createQuery("select e from " + entityName + " e"));
}
break;
}
}
}
}
return map == null ? Collections.<Query>emptyList() : map.values();
}
use of com.blazebit.persistence.spi.JpaMetamodelAccessor in project blaze-persistence by Blazebit.
the class AbstractModificationCriteriaBuilder method getExampleQuery.
private TypedQuery<Object[]> getExampleQuery(List<List<Attribute<?, ?>>> attributes) {
StringBuilder sb = new StringBuilder();
StringBuilder joinSb = new StringBuilder();
sb.append("SELECT ");
boolean first = true;
for (List<Attribute<?, ?>> attrPath : attributes) {
Attribute<?, ?> lastPathElem = attrPath.get(attrPath.size() - 1);
if (first) {
first = false;
} else {
sb.append(",");
}
// TODO: actually we should also check if the attribute is a @GeneratedValue
if (!mainQuery.dbmsDialect.supportsReturningColumns() && !JpaMetamodelUtils.getSingleIdAttribute(entityType).equals(lastPathElem)) {
throw new IllegalArgumentException("Returning the query attribute [" + lastPathElem.getName() + "] is not supported by the dbms, only generated keys can be returned!");
}
JpaMetamodelAccessor jpaMetamodelAccessor = mainQuery.jpaProvider.getJpaMetamodelAccessor();
if (jpaMetamodelAccessor.isJoinable(lastPathElem)) {
sb.append(entityAlias).append('.');
// We have to map *-to-one relationships to their ids
EntityType<?> type = mainQuery.metamodel.entity(JpaMetamodelUtils.resolveFieldClass(entityType.getJavaType(), lastPathElem));
Attribute<?, ?> idAttribute = JpaMetamodelUtils.getSingleIdAttribute(type);
// NOTE: Since we are talking about *-to-ones, the expression can only be a path to an object
// so it is safe to just append the id to the path
sb.append(lastPathElem.getName()).append('.').append(idAttribute.getName());
} else {
String startAlias = entityAlias;
int startIndex = 0;
// To support this, we need to add a join to the example query
for (int i = 0; i < attrPath.size(); i++) {
if (attrPath.get(i).isCollection()) {
startAlias = attrPath.get(i).getName();
startIndex = i + 1;
joinSb.append(" JOIN ").append(entityAlias).append(".").append(startAlias).append(" ").append(startAlias);
break;
}
}
sb.append(startAlias).append('.');
sb.append(attrPath.get(startIndex).getName());
for (int i = startIndex + 1; i < attrPath.size(); i++) {
sb.append('.').append(attrPath.get(i).getName());
}
}
}
sb.append(" FROM ");
sb.append(entityType.getName()).append(' ').append(entityAlias);
sb.append(joinSb);
String exampleQueryString = sb.toString();
return em.createQuery(exampleQueryString, Object[].class);
}
use of com.blazebit.persistence.spi.JpaMetamodelAccessor in project blaze-persistence by Blazebit.
the class AbstractModificationCriteriaBuilder method getAndCheckAttributes.
private List<List<Attribute<?, ?>>> getAndCheckAttributes(String[] attributes) {
List<List<Attribute<?, ?>>> attrs = new ArrayList<List<Attribute<?, ?>>>(attributes.length);
for (int i = 0; i < attributes.length; i++) {
if (attributes[i] == null) {
throw new NullPointerException("attribute at position " + i);
}
if (attributes[i].isEmpty()) {
throw new IllegalArgumentException("empty attribute at position " + i);
}
JpaMetamodelAccessor jpaMetamodelAccessor = mainQuery.jpaProvider.getJpaMetamodelAccessor();
attrs.add(jpaMetamodelAccessor.getBasicAttributePath(getMetamodel(), entityType, attributes[i]).getAttributes());
}
return attrs;
}
use of com.blazebit.persistence.spi.JpaMetamodelAccessor in project blaze-persistence by Blazebit.
the class JoinManager method implicitJoinSingle.
private JoinResult implicitJoinSingle(JoinNode baseNode, String attributeName, String treatTypeName, JoinType joinType, JoinNode currentJoinNode, boolean objectLeafAllowed, boolean joinRequired, boolean joinAllowed, boolean singularJoinAllowed) {
JoinNode newBaseNode;
String field;
Type<?> type;
boolean lazy = false;
Type<?> baseNodeType = baseNode.getNodeType();
// The given path may be relative to the root or it might be an alias
if (objectLeafAllowed) {
AttributeHolder attributeHolder = JpaUtils.getAttributeForJoining(metamodel, baseNodeType, expressionFactory.createJoinPathExpression(attributeName), null);
Attribute<?, ?> attr = attributeHolder.getAttribute();
if (attr == null) {
throw new IllegalArgumentException("Field with name '" + attributeName + "' was not found within managed type " + JpaMetamodelUtils.getTypeName(baseNodeType));
}
if (joinRequired || attr.isCollection()) {
final JoinResult newBaseNodeResult = implicitJoinSingle(baseNode, attributeName, treatTypeName, joinType, currentJoinNode, false, joinAllowed, singularJoinAllowed);
newBaseNode = newBaseNodeResult.baseNode;
// check if the last path element was also joined
if (newBaseNode != baseNode) {
field = null;
type = newBaseNode.getNodeType();
} else {
field = attributeName;
type = attributeHolder.getAttributeType();
}
} else {
newBaseNode = baseNode;
field = attributeName;
type = attributeHolder.getAttributeType();
lazy = true;
}
} else {
JpaMetamodelAccessor jpaMetamodelAccessor = mainQuery.jpaProvider.getJpaMetamodelAccessor();
AttributeHolder attributeHolder = JpaUtils.getAttributeForJoining(metamodel, baseNodeType, expressionFactory.createJoinPathExpression(attributeName), null);
Attribute<?, ?> attr = attributeHolder.getAttribute();
if (attr == null) {
throw new IllegalArgumentException("Field with name " + attributeName + " was not found within class " + JpaMetamodelUtils.getTypeName(baseNodeType));
}
if (jpaMetamodelAccessor.isJoinable(attr)) {
if (jpaMetamodelAccessor.isCompositeNode(attr)) {
throw new IllegalArgumentException("No object leaf allowed but " + attributeName + " is an object leaf");
} else {
final JoinResult newBaseNodeResult = implicitJoinSingle(baseNode, attributeName, treatTypeName, joinType, currentJoinNode, false, joinAllowed, singularJoinAllowed);
newBaseNode = newBaseNodeResult.baseNode;
field = null;
type = newBaseNode.getNodeType();
}
} else {
newBaseNode = baseNode;
field = attributeName;
type = attributeHolder.getAttributeType();
}
}
return new JoinResult(newBaseNode, field == null ? null : Arrays.asList(field), type, -1, -1, lazy);
}
Aggregations