use of com.blazebit.persistence.parser.EntityMetamodel in project blaze-persistence by Blazebit.
the class Mappers method forViewToEntityAttributeMapping.
public static <S, T> Mapper<S, T> forViewToEntityAttributeMapping(EntityViewManagerImpl evm, ManagedViewType<S> sourceViewType, Class<T> targetEntityClass, Map<String, String> mapping) {
EntityMetamodel metamodel = evm.getCriteriaBuilderFactory().getService(EntityMetamodel.class);
List<AttributeAccessor> source = new ArrayList<>(mapping.size());
List<AttributeAccessor> target = new ArrayList<>(mapping.size());
for (Map.Entry<String, String> entry : mapping.entrySet()) {
source.add(Accessors.forViewAttributePath(evm, sourceViewType, entry.getKey(), true));
target.add(Accessors.forEntityMapping(evm, targetEntityClass, entry.getValue()));
}
return new AttributeMapper<>(source, target);
}
use of com.blazebit.persistence.parser.EntityMetamodel in project blaze-persistence by Blazebit.
the class BlazeCriteriaBuilderRenderer method serializeSubQuery.
private Object serializeSubQuery(Object criteriaBuilder, Expression<?> expression) {
Object result = expression.accept(new Visitor<Object, Object>() {
@Override
public Object visit(Constant<?> constant, Object criteriaBuilder) {
throw new UnsupportedOperationException();
}
@Override
public Object visit(FactoryExpression<?> factoryExpression, Object criteriaBuilder) {
throw new UnsupportedOperationException();
}
@Override
public Object visit(Operation<?> setOperation, Object criteriaBuilder) {
Expression<?> lhs = setOperation.getArg(0);
SubQueryExpression<?> lhsSubquery = lhs.accept(GetSubQueryVisitor.INSTANCE, null);
SetOperationFlag setOperationFlag = lhsSubquery != null ? getSetOperationFlag(lhsSubquery.getMetadata()) : null;
boolean lhsNestedSet = setOperationFlag != null && LEFT_NESTED_SET_OPERATIONS.contains(setOperation.getOperator());
if (lhsNestedSet) {
if (criteriaBuilder instanceof StartOngoingSetOperationBuilder) {
StartOngoingSetOperationBuilder<?, ?, ?> ob = (StartOngoingSetOperationBuilder<?, ?, ?>) criteriaBuilder;
criteriaBuilder = ob.startSet();
} else if (criteriaBuilder instanceof SubqueryInitiator) {
SubqueryInitiator<?> subqueryInitiator = (SubqueryInitiator<?>) criteriaBuilder;
criteriaBuilder = subqueryInitiator.startSet();
} else {
criteriaBuilder = criteriaBuilderFactory.startSet(entityManager, Object.class);
}
criteriaBuilder = setOperationFlag.getFlag().accept(this, criteriaBuilder);
if (criteriaBuilder instanceof OngoingSetOperationBuilder) {
criteriaBuilder = ((OngoingSetOperationBuilder<?, ?, ?>) criteriaBuilder).endSetWith();
renderOrderBy(lhsSubquery.getMetadata(), (OrderByBuilder<?>) criteriaBuilder);
renderModifiers(lhsSubquery.getMetadata().getModifiers(), (LimitBuilder<?>) criteriaBuilder);
criteriaBuilder = ((BaseOngoingFinalSetOperationBuilder) criteriaBuilder).endSet();
} else {
throw new UnsupportedOperationException();
}
} else {
criteriaBuilder = lhs.accept(this, criteriaBuilder);
}
Expression<?> rhs = setOperation.getArg(1);
SubQueryExpression<?> rhsSubquery = rhs.accept(GetSubQueryVisitor.INSTANCE, null);
setOperationFlag = rhsSubquery != null ? getSetOperationFlag(rhsSubquery.getMetadata()) : null;
boolean isNestedSet = setOperationFlag != null;
SetOperationBuilder<?, ?> setOperationBuilder = (SetOperationBuilder<?, ?>) criteriaBuilder;
switch((JPQLNextOps) setOperation.getOperator()) {
// CHECKSTYLE:OFF: FallThrough
case SET_UNION:
case LEFT_NESTED_SET_UNION:
criteriaBuilder = isNestedSet ? setOperationBuilder.startUnion() : setOperationBuilder.union();
break;
case SET_UNION_ALL:
case LEFT_NESTED_SET_UNION_ALL:
criteriaBuilder = isNestedSet ? setOperationBuilder.startUnionAll() : setOperationBuilder.unionAll();
break;
case SET_EXCEPT:
case LEFT_NESTED_SET_EXCEPT:
criteriaBuilder = isNestedSet ? setOperationBuilder.startExcept() : setOperationBuilder.except();
break;
case SET_EXCEPT_ALL:
case LEFT_NESTED_SET_EXCEPT_ALL:
criteriaBuilder = isNestedSet ? setOperationBuilder.startExceptAll() : setOperationBuilder.exceptAll();
break;
case SET_INTERSECT:
case LEFT_NESTED_SET_INTERSECT:
criteriaBuilder = isNestedSet ? setOperationBuilder.startIntersect() : setOperationBuilder.intersect();
break;
case SET_INTERSECT_ALL:
case LEFT_NESTED_SET_INTERSECT_ALL:
criteriaBuilder = isNestedSet ? setOperationBuilder.startIntersectAll() : setOperationBuilder.intersectAll();
break;
default:
throw new UnsupportedOperationException("No support for set operation " + setOperation.getOperator());
}
if (isNestedSet) {
criteriaBuilder = setOperationFlag.getFlag().accept(this, criteriaBuilder);
if (criteriaBuilder instanceof OngoingSetOperationBuilder) {
criteriaBuilder = ((OngoingSetOperationBuilder<?, ?, ?>) criteriaBuilder).endSetWith();
renderOrderBy(rhsSubquery.getMetadata(), (OrderByBuilder<?>) criteriaBuilder);
renderModifiers(rhsSubquery.getMetadata().getModifiers(), (LimitBuilder<?>) criteriaBuilder);
criteriaBuilder = ((BaseOngoingFinalSetOperationBuilder) criteriaBuilder).endSet();
} else {
throw new UnsupportedOperationException();
}
} else {
criteriaBuilder = rhs.accept(this, criteriaBuilder);
}
return criteriaBuilder;
}
@Override
public Object visit(ParamExpression<?> paramExpression, Object criteriaBuilder) {
throw new UnsupportedOperationException();
}
@Override
public Object visit(Path<?> path, Object criteriaBuilder) {
throw new UnsupportedOperationException();
}
@Override
public Object visit(SubQueryExpression<?> subQuery, Object criteriaBuilder) {
QueryMetadata subQueryMetadata = subQuery.getMetadata();
SetOperationFlag setOperationFlag = getSetOperationFlag(subQueryMetadata);
if (setOperationFlag != null) {
return setOperationFlag.getFlag().accept(this, criteriaBuilder);
}
renderCTEs(subQueryMetadata);
criteriaBuilder = renderJoins(subQueryMetadata, (FromBaseBuilder) criteriaBuilder);
criteriaBuilder = renderNamedWindows(subQueryMetadata, (WindowContainerBuilder) criteriaBuilder);
renderDistinct(subQueryMetadata, (DistinctBuilder<?>) criteriaBuilder);
renderWhere(subQueryMetadata, (WhereBuilder<?>) criteriaBuilder);
renderGroupBy(subQueryMetadata, (GroupByBuilder<?>) criteriaBuilder);
renderHaving(subQueryMetadata, (HavingBuilder<?>) criteriaBuilder);
Expression<?> select = subQueryMetadata.getProjection();
if (select instanceof FactoryExpression<?> && criteriaBuilder instanceof FullQueryBuilder<?, ?>) {
FactoryExpression<T> factoryExpression = (FactoryExpression<T>) select;
FullQueryBuilder<?, ?> fullQueryBuilder = (FullQueryBuilder<?, ?>) criteriaBuilder;
criteriaBuilder = fullQueryBuilder.selectNew(new FactoryExpressionObjectBuilder(factoryExpression));
} else {
List<? extends Expression<?>> projection = expandProjection(subQueryMetadata.getProjection());
if (criteriaBuilder instanceof SelectBaseCTECriteriaBuilder) {
SelectBaseCTECriteriaBuilder<?> selectBaseCriteriaBuilder = (SelectBaseCTECriteriaBuilder<?>) criteriaBuilder;
boolean bindEntity = projection.size() == 1 && subQueryMetadata.getJoins().get(0).getTarget().accept(new JoinTargetAliasPathResolver(), null).equals(projection.get(0));
if (bindEntity) {
EntityMetamodel metamodel = criteriaBuilderFactory.getService(EntityMetamodel.class);
Path<?> pathExpression = (Path<?>) projection.get(0);
ExtendedManagedType<?> managedType = metamodel.getManagedType(ExtendedManagedType.class, pathExpression.getType());
Map<String, ? extends ExtendedAttribute<?, ?>> ownedSingularAttributes = managedType.getOwnedSingularAttributes();
for (Map.Entry<String, ? extends ExtendedAttribute<?, ?>> ownedSingularAttribute : ownedSingularAttributes.entrySet()) {
String attributeName = ownedSingularAttribute.getKey();
ExtendedAttribute<?, ?> attribute = ownedSingularAttribute.getValue();
if (!JpaMetamodelUtils.isAssociation(attribute.getAttribute())) {
final SelectBuilder<?> bindBuilder = selectBaseCriteriaBuilder.bind(attributeName);
BeanPath<?> beanPath = new BeanPath<Object>(attribute.getElementClass(), pathExpression, attributeName);
setExpressionSubqueries(beanPath, null, bindBuilder, SelectBuilderExpressionSetter.INSTANCE);
}
}
} else {
for (int i = 0; i < projection.size(); i++) {
Expression<?> projExpression = projection.get(i);
BindResolverContext bindResolverContext = new BindResolverContext();
projExpression = projExpression.accept(BindResolver.INSTANCE, bindResolverContext);
Path<?> cteAttribute = bindResolverContext.getCteAttribute();
String alias = bindResolverContext.getAliasString();
if (cteAttribute == null && cteAliases != null) {
cteAttribute = cteAliases.get(i);
}
if (cteAttribute != null) {
Path<?> cteEntityPath = cteAttribute.getRoot();
String relativeCteAttributePath = relativePathString(cteEntityPath, cteAttribute);
final SelectBuilder<?> bindBuilder = selectBaseCriteriaBuilder.bind(relativeCteAttributePath);
setExpressionSubqueries(projExpression, alias, bindBuilder, SelectBuilderExpressionSetter.INSTANCE);
} else {
throw new UnsupportedOperationException("Select statement should be bound to any CTE attribute");
}
}
}
} else {
for (Expression<?> selection : projection) {
renderSingleSelect(selection, (SelectBuilder<?>) criteriaBuilder);
}
}
}
renderOrderBy(subQueryMetadata, (OrderByBuilder<?>) criteriaBuilder);
renderParameters(subQueryMetadata, (ParameterHolder<?>) criteriaBuilder);
// Limit / offset on full query is set outside of the renderer, based on whether we're rendering a full count query or not
if (!(criteriaBuilder instanceof Queryable)) {
renderModifiers(subQueryMetadata.getModifiers(), (LimitBuilder<?>) criteriaBuilder);
}
return criteriaBuilder;
}
@Override
public Object visit(TemplateExpression<?> templateExpression, Object criteriaBuilder) {
throw new UnsupportedOperationException();
}
}, criteriaBuilder);
if (result instanceof BaseOngoingSetOperationBuilder) {
result = ((BaseOngoingSetOperationBuilder<?, ?, ?>) result).endSet();
}
if ((result instanceof FinalSetOperationCriteriaBuilder || result instanceof FinalSetOperationCTECriteriaBuilder || result instanceof FinalSetOperationSubqueryBuilder) && expression instanceof SubQueryExpression<?>) {
QueryMetadata metadata = ((SubQueryExpression<?>) expression).getMetadata();
renderOrderBy(metadata, (OrderByBuilder<?>) result);
// Limit / offset on full query is set outside of the renderer, based on whether we're rendering a full count query or not
if (!(criteriaBuilder instanceof Queryable)) {
renderModifiers(metadata.getModifiers(), (LimitBuilder<?>) result);
}
}
return result;
}
use of com.blazebit.persistence.parser.EntityMetamodel in project blaze-persistence by Blazebit.
the class InverseFlusher method forAttribute.
public static <E> InverseFlusher<E> forAttribute(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, ManagedViewType<?> viewType, AbstractMethodAttribute<?, ?> attribute, TypeDescriptor childTypeDescriptor, EntityViewUpdaterImpl owner, String ownerMapping) {
if (attribute.getMappedBy() != null) {
String attributeLocation = attribute.getLocation();
Type<?> elementType = attribute instanceof PluralAttribute<?, ?, ?> ? ((PluralAttribute<?, ?, ?>) attribute).getElementType() : ((SingularAttribute<?, ?>) attribute).getType();
Class<?> elementEntityClass = null;
AttributeAccessor parentReferenceAttributeAccessor = null;
Mapper<Object, Object> parentEntityOnChildViewMapper = null;
Mapper<Object, Object> parentEntityOnChildEntityAddMapper = null;
Mapper<Object, Object> parentEntityOnChildEntityRemoveMapper = null;
TargetViewClassBasedInverseViewToEntityMapper childViewToEntityMapper = null;
InverseEntityToEntityMapper childEntityToEntityMapper = null;
ViewToEntityMapper parentReferenceViewToEntityMapper = new LoadOnlyViewToEntityMapper(new ReferenceEntityLoader(evm, viewType, EntityViewUpdaterImpl.createViewIdMapper(evm, localCache, viewType)), Accessors.forViewId(evm, (ViewType<?>) viewType, true), evm.getEntityIdAccessor());
ViewToEntityMapper childReferenceViewToEntityMapper = null;
TypeDescriptor parentReferenceTypeDescriptor = TypeDescriptor.forInverseAttribute(parentReferenceViewToEntityMapper);
if (attribute.getWritableMappedByMappings() != null) {
// This happens when the mapped by attribute is insertable=false and updatable=false
if (childTypeDescriptor.isSubview()) {
ViewType<?> childViewType = (ViewType<?>) elementType;
elementEntityClass = childViewType.getEntityClass();
Map<Class<?>, Mapper<Object, Object>> mappers = new HashMap<>();
for (ManagedViewType<?> type : attribute.getViewTypes()) {
Mapper<Object, Object> mapper = Mappers.forViewConvertToViewAttributeMapping(evm, (ViewType<Object>) viewType, (ViewType<Object>) type, attribute.getWritableMappedByMappings(), (Mapper<Object, Object>) Mappers.forEntityAttributeMappingConvertToViewAttributeMapping(evm, viewType.getEntityClass(), type, attribute.getWritableMappedByMappings()));
if (mapper == null) {
mapper = NoopMapper.INSTANCE;
}
mappers.put(type.getJavaType(), mapper);
}
parentEntityOnChildViewMapper = (Mapper<Object, Object>) Mappers.targetViewClassBasedMapper(mappers);
parentEntityOnChildEntityAddMapper = parentEntityOnChildEntityRemoveMapper = (Mapper<Object, Object>) Mappers.forEntityAttributeMapping(evm, viewType.getEntityClass(), childViewType.getEntityClass(), attribute.getWritableMappedByMappings());
childReferenceViewToEntityMapper = new LoadOrPersistViewToEntityMapper(attributeLocation, evm, childViewType.getJavaType(), attribute.getReadOnlyAllowedSubtypes(), attribute.getPersistCascadeAllowedSubtypes(), attribute.getUpdateCascadeAllowedSubtypes(), new ReferenceEntityLoader(evm, childViewType, EntityViewUpdaterImpl.createViewIdMapper(evm, localCache, childViewType)), Accessors.forViewId(evm, childViewType, true), evm.getEntityIdAccessor(), true, owner, ownerMapping, localCache);
} else if (childTypeDescriptor.isJpaEntity()) {
Class<?> childType = elementType.getJavaType();
elementEntityClass = childType;
parentEntityOnChildViewMapper = (Mapper<Object, Object>) Mappers.forEntityAttributeMapping(evm, viewType.getEntityClass(), childType, attribute.getWritableMappedByMappings());
parentEntityOnChildEntityAddMapper = parentEntityOnChildEntityRemoveMapper = (Mapper<Object, Object>) Mappers.forEntityAttributeMapping(evm, viewType.getEntityClass(), elementEntityClass, attribute.getWritableMappedByMappings());
}
} else {
if (childTypeDescriptor.isSubview()) {
ViewType<?> childViewType = (ViewType<?>) elementType;
elementEntityClass = childViewType.getEntityClass();
parentReferenceAttributeAccessor = Accessors.forEntityMapping(evm, childViewType.getEntityClass(), attribute.getMappedBy());
childReferenceViewToEntityMapper = new LoadOrPersistViewToEntityMapper(attributeLocation, evm, childViewType.getJavaType(), attribute.getReadOnlyAllowedSubtypes(), attribute.getPersistCascadeAllowedSubtypes(), attribute.getUpdateCascadeAllowedSubtypes(), new ReferenceEntityLoader(evm, childViewType, EntityViewUpdaterImpl.createViewIdMapper(evm, localCache, childViewType)), Accessors.forViewId(evm, childViewType, true), evm.getEntityIdAccessor(), true, owner, ownerMapping, localCache);
parentEntityOnChildEntityAddMapper = parentEntityOnChildEntityRemoveMapper = Mappers.forAccessor(parentReferenceAttributeAccessor);
Map<Class<?>, Mapper<Object, Object>> mappers = new HashMap<>();
for (ManagedViewType<?> type : attribute.getViewTypes()) {
Mapper<Object, Object> mapper = (Mapper<Object, Object>) Mappers.forViewConvertToViewAttributeMapping(evm, (ViewType<Object>) viewType, (ViewType<Object>) type, attribute.getMappedBy(), null);
if (mapper == null) {
mapper = NoopMapper.INSTANCE;
}
mappers.put(type.getJavaType(), mapper);
}
parentEntityOnChildViewMapper = (Mapper<Object, Object>) Mappers.targetViewClassBasedMapper(mappers);
} else if (childTypeDescriptor.isJpaEntity()) {
Class<?> childType = elementType.getJavaType();
elementEntityClass = childType;
parentReferenceAttributeAccessor = Accessors.forEntityMapping(evm, childType, attribute.getMappedBy());
parentEntityOnChildEntityAddMapper = parentEntityOnChildEntityRemoveMapper = Mappers.forAccessor(parentReferenceAttributeAccessor);
parentEntityOnChildViewMapper = Mappers.forAccessor(parentReferenceAttributeAccessor);
}
}
DirtyAttributeFlusher<?, Object, ? extends Object> parentReferenceAttributeFlusher;
ManagedType<?> managedType = evm.getMetamodel().getEntityMetamodel().getManagedType(elementEntityClass);
Attribute<?, ?> inverseAttribute = JpaMetamodelUtils.getAttribute(managedType, attribute.getMappedBy());
// Many-To-Many relation can't be handled by the inverse flushers
if (inverseAttribute != null && inverseAttribute.isCollection()) {
// A collection can only have a single attribute, so it's safe to assume a SimpleMapper
parentEntityOnChildEntityAddMapper = new CollectionAddMapper<>(parentEntityOnChildEntityAddMapper == null ? parentReferenceAttributeAccessor : ((SimpleMapper<Object, Object>) parentEntityOnChildEntityAddMapper).getAttributeAccessor());
parentEntityOnChildEntityRemoveMapper = new CollectionRemoveMapper<>(parentEntityOnChildEntityRemoveMapper == null ? parentReferenceAttributeAccessor : ((SimpleMapper<Object, Object>) parentEntityOnChildEntityRemoveMapper).getAttributeAccessor());
parentReferenceAttributeFlusher = new ParentCollectionReferenceAttributeFlusher<>(attributeLocation, attribute.getMappedBy(), viewType.getFlushStrategy(), parentReferenceAttributeAccessor, null, null, null, TypeDescriptor.forInverseCollectionAttribute(viewType.getEntityClass(), new EntityBasicUserType(evm.getJpaProvider())));
} else {
parentEntityOnChildEntityRemoveMapper = new NullMapper<>(parentEntityOnChildEntityRemoveMapper);
parentReferenceAttributeFlusher = new ParentReferenceAttributeFlusher<>(evm, viewType.getEntityClass(), attributeLocation, attribute.getMappedBy(), attribute.getWritableMappedByMappings(), parentReferenceTypeDescriptor, parentReferenceAttributeAccessor, parentEntityOnChildViewMapper);
}
UnmappedAttributeCascadeDeleter deleter = null;
String parentIdAttributeName = null;
String childIdAttributeName = null;
Class<?> childIdViewClass = null;
// Only construct when orphanRemoval or delete cascading is enabled, orphanRemoval implies delete cascading
if (attribute.isDeleteCascaded()) {
EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
ExtendedManagedType<?> ownerManagedType = entityMetamodel.getManagedType(ExtendedManagedType.class, viewType.getEntityClass());
ExtendedManagedType<?> elementManagedType = entityMetamodel.getManagedType(ExtendedManagedType.class, elementEntityClass);
parentIdAttributeName = ownerManagedType.getIdAttribute().getName();
childIdAttributeName = elementManagedType.getIdAttribute().getName();
String mapping = attribute.getMappedBy();
if (mapping != null) {
if (mapping.isEmpty()) {
deleter = new UnmappedWritableBasicAttributeSetNullCascadeDeleter(evm, ownerManagedType.getType(), elementManagedType, attribute.getWritableMappedByMappings());
} else {
ExtendedAttribute extendedAttribute = elementManagedType.getAttribute(mapping);
if (childTypeDescriptor.isSubview()) {
if (elementType instanceof ViewType<?>) {
MethodAttribute<?, ?> idAttribute = ((ViewType<?>) elementType).getIdAttribute();
if (idAttribute.isSubview()) {
// in this case, we need to fetch the id as view as the deleter expects it this way
childIdViewClass = idAttribute.getJavaType();
}
}
deleter = new ViewTypeCascadeDeleter(childTypeDescriptor.getViewToEntityMapper());
} else if (childTypeDescriptor.isJpaEntity()) {
deleter = new UnmappedBasicAttributeCascadeDeleter(evm, mapping, extendedAttribute, mapping + "." + parentIdAttributeName, false);
}
}
}
}
if (childTypeDescriptor.isSubview()) {
InverseViewToEntityMapper<?> first = null;
Map<Class<?>, InverseViewToEntityMapper<?>> mappers = new HashMap<>();
for (ManagedViewType<?> type : attribute.getViewTypes()) {
InverseViewToEntityMapper inverseViewToEntityMapper = new InverseViewToEntityMapper(evm, localCache, (ViewType<?>) type, parentEntityOnChildViewMapper, parentEntityOnChildEntityAddMapper, parentEntityOnChildEntityRemoveMapper, childTypeDescriptor.getViewToEntityMapper(), parentReferenceAttributeFlusher, EntityViewUpdaterImpl.createIdFlusher(evm, localCache, (ViewType<?>) type, EntityViewUpdaterImpl.createViewIdMapper(evm, localCache, type)));
mappers.put(type.getJavaType(), inverseViewToEntityMapper);
if (type == elementType) {
first = inverseViewToEntityMapper;
}
}
childViewToEntityMapper = new TargetViewClassBasedInverseViewToEntityMapper(first, mappers);
} else if (childTypeDescriptor.isJpaEntity()) {
Class<?> childType = elementType.getJavaType();
childEntityToEntityMapper = new InverseEntityToEntityMapper(evm, evm.getMetamodel().getEntityMetamodel().entity(childType), parentEntityOnChildEntityAddMapper, parentEntityOnChildEntityRemoveMapper, parentReferenceAttributeFlusher);
}
return new InverseFlusher(viewType.getEntityClass(), attribute.getMapping(), parentIdAttributeName, childIdAttributeName, childIdViewClass, deleter, parentReferenceViewToEntityMapper, parentReferenceAttributeFlusher, parentEntityOnChildViewMapper, childViewToEntityMapper, childReferenceViewToEntityMapper, parentEntityOnChildEntityAddMapper, childEntityToEntityMapper);
}
return null;
}
use of com.blazebit.persistence.parser.EntityMetamodel in project blaze-persistence by Blazebit.
the class EntityViewUpdaterImpl method createPluralAttributeSubFlusher.
private DirtyAttributeFlusher<?, ?, ?> createPluralAttributeSubFlusher(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, ManagedViewTypeImplementor<?> viewType, AbstractMethodAttribute<?, ?> attribute, String name, Type<?> type, EntityViewUpdaterImpl owner, String ownerMapping) {
EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
String attributeName = attribute.getName() + "_" + name;
String attributeMapping = attribute.getMapping();
String attributeLocation = attribute.getLocation();
Set<Type<?>> readOnlyAllowedSubtypes = attribute.getReadOnlyAllowedSubtypes();
Set<Type<?>> persistAllowedSubtypes = attribute.getPersistCascadeAllowedSubtypes();
Set<Type<?>> updateAllowedSubtypes = attribute.getUpdateCascadeAllowedSubtypes();
if (type instanceof ManagedViewType<?>) {
ManagedViewTypeImplementor<?> subviewType = (ManagedViewTypeImplementor<?>) type;
if (!(subviewType.getJpaManagedType() instanceof EntityType<?>)) {
// A singular attribute where the subview refers to an embeddable type
EmbeddableUpdaterBasedViewToEntityMapper viewToEntityMapper = new EmbeddableUpdaterBasedViewToEntityMapper(attributeLocation, evm, subviewType.getJavaType(), readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, subviewType, attribute), false, null, owner, ownerMapping == null ? attributeMapping : ownerMapping + "." + attributeMapping, localCache);
String parameterName = attributeName + "_";
String updateFragment = attributeMapping + ".";
return new EmbeddableAttributeFlusher<>(attributeName, attributeMapping, updateFragment, parameterName, false, false, false, null, null, viewToEntityMapper);
} else {
ViewTypeImplementor<?> attributeViewType = (ViewTypeImplementor<?>) subviewType;
InitialValueAttributeAccessor viewAttributeAccessor = Accessors.forMutableViewAttribute(evm, attribute);
AttributeAccessor subviewIdAccessor;
ManagedType<?> ownerManagedType = owner == null ? viewType.getJpaManagedType() : owner.managedViewType.getJpaManagedType();
EntityType<?> ownerEntityType = ownerManagedType instanceof EntityType<?> ? (EntityType<?>) ownerManagedType : null;
String attributeElementIdMapping;
if (ownerEntityType != null && attribute.getMapping() != null) {
ExtendedManagedType<?> extendedManagedType = evm.getMetamodel().getEntityMetamodel().getManagedType(ExtendedManagedType.class, attributeViewType.getEntityClass());
attributeElementIdMapping = TypeDescriptor.getAttributeElementIdentifier(evm, ownerEntityType, attribute.getName(), ownerMapping, attribute.getMapping(), extendedManagedType.getType());
} else {
attributeElementIdMapping = ((MappingAttribute<?, ?>) attributeViewType.getIdAttribute()).getMapping();
}
subviewIdAccessor = Accessors.forSubviewAssociationId(evm, attributeViewType, attributeElementIdMapping, true);
Attribute<?, ?> attributeIdAttribute = attributeViewType.getJpaManagedType().getAttribute(attributeElementIdMapping);
javax.persistence.metamodel.Type<?> attributeIdAttributeType = entityMetamodel.type(JpaMetamodelUtils.resolveFieldClass(attributeViewType.getEntityClass(), attributeIdAttribute));
List<String> idComponentMappings;
boolean requiresComponentWiseSetInUpdate = true;
if (requiresComponentWiseSetInUpdate && attributeIdAttributeType instanceof EmbeddableType<?>) {
// If the identifier used for the association is an embeddable, we must collect the individual attribute components since updates don't work on embeddables directly
Set<Attribute<?, ?>> idAttributeComponents = (Set<Attribute<?, ?>>) ((EmbeddableType<?>) attributeIdAttributeType).getAttributes();
idComponentMappings = new ArrayList<>(idAttributeComponents.size());
for (Attribute<?, ?> idAttributeComponent : idAttributeComponents) {
idComponentMappings.add(attributeMapping + "." + attributeElementIdMapping + "." + idAttributeComponent);
}
} else {
idComponentMappings = Collections.singletonList(attributeMapping + "." + attributeElementIdMapping);
}
String[] idAttributeMappings = idComponentMappings.toArray(new String[idComponentMappings.size()]);
ViewToEntityMapper viewToEntityMapper = createViewToEntityMapper(attributeLocation, evm, localCache, ownerEntityType, attributeName, attributeMapping, attributeViewType, false, false, readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, attributeViewType, attribute.getViewTypes(), attributeElementIdMapping), owner, ownerMapping);
String parameterName = attributeName;
return new SubviewAttributeFlusher<>(attributeName, attributeMapping, false, true, false, false, false, subviewType.getConverter(), false, idAttributeMappings, parameterName, false, owner != null, null, viewAttributeAccessor, subviewIdAccessor, viewToEntityMapper, null, null);
}
} else {
TypeDescriptor elementDescriptor = TypeDescriptor.forType(evm, localCache, this, attribute, type, owner, ownerMapping);
String parameterName = attributeName;
String updateFragment = attributeMapping;
// TODO: Why?
boolean supportsQueryFlush = !elementDescriptor.isJpaEmbeddable();
return new BasicAttributeFlusher<>(attributeName, attributeMapping, supportsQueryFlush, false, true, false, false, false, null, elementDescriptor, updateFragment, parameterName, null, null, null, null, null);
}
}
use of com.blazebit.persistence.parser.EntityMetamodel in project blaze-persistence by Blazebit.
the class TypeDescriptor method forType.
public static TypeDescriptor forType(EntityViewManagerImpl evm, Map<Object, EntityViewUpdaterImpl> localCache, EntityViewUpdaterImpl updater, AbstractMethodAttribute<?, ?> attribute, Type<?> type, EntityViewUpdaterImpl owner, String ownerMapping) {
EntityMetamodel entityMetamodel = evm.getMetamodel().getEntityMetamodel();
String attributeLocation = attribute.getLocation();
boolean cascadePersist = attribute.isPersistCascaded();
boolean cascadeUpdate = attribute.isUpdateCascaded();
Set<Type<?>> readOnlyAllowedSubtypes = attribute.getReadOnlyAllowedSubtypes();
Set<Type<?>> persistAllowedSubtypes = attribute.getPersistCascadeAllowedSubtypes();
Set<Type<?>> updateAllowedSubtypes = attribute.getUpdateCascadeAllowedSubtypes();
EntityToEntityMapper entityToEntityMapper = null;
ViewToEntityMapper viewToEntityMapper = null;
ViewToEntityMapper loadOnlyViewToEntityMapper = null;
final ManagedType<?> managedType = entityMetamodel.getManagedType(type.getJavaType());
final boolean jpaEntity = managedType instanceof EntityType<?>;
final boolean jpaManaged = managedType != null;
final boolean mutable;
final boolean identifiable;
TypeConverter<Object, Object> converter = (TypeConverter<Object, Object>) type.getConverter();
BasicUserType<Object> basicUserType;
ManagedType<?> ownerEntityType = owner == null ? attribute.getDeclaringType().getJpaManagedType() : owner.getManagedViewType().getJpaManagedType();
String attributeIdAttributeName = null;
String entityIdAttributeName = null;
Class<?> jpaType;
// TODO: currently we only check if the declared type is mutable, but we have to let the collection flusher which types are considered updatable/creatable
if (type instanceof BasicType<?>) {
jpaType = type.getJavaType();
basicUserType = (BasicUserType<Object>) ((BasicType<?>) type).getUserType();
mutable = basicUserType.isMutable();
identifiable = jpaEntity || !jpaManaged;
if (jpaEntity) {
Map<String, Map<?, ?>> fetchGraph = null;
UnmappedAttributeCascadeDeleter deleter = null;
// We only need to know the fetch graph when we actually do updates
if (cascadeUpdate) {
fetchGraph = getFetchGraph(attribute.getFetches(), attribute.getMapping(), managedType);
}
if (ownerEntityType instanceof EntityType<?>) {
ExtendedManagedType<?> extendedManagedType = evm.getMetamodel().getEntityMetamodel().getManagedType(ExtendedManagedType.class, type.getJavaType());
entityIdAttributeName = extendedManagedType.getIdAttribute().getName();
attributeIdAttributeName = getAttributeElementIdentifier(evm, (EntityType<?>) ownerEntityType, attribute.getName(), ownerMapping, attribute.getMapping(), extendedManagedType.getType());
// Only construct when orphanRemoval or delete cascading is enabled, orphanRemoval implies delete cascading
if (attribute.isDeleteCascaded()) {
String mapping = attribute.getMapping();
ExtendedManagedType elementManagedType = entityMetamodel.getManagedType(ExtendedManagedType.class, attribute.getDeclaringType().getJpaManagedType());
deleter = new UnmappedBasicAttributeCascadeDeleter(evm, mapping, elementManagedType.getAttribute(mapping), mapping + "." + attributeIdAttributeName, false);
}
}
// TODO: EntityToEntityMapper should also use the attributeIdAttributeName
entityToEntityMapper = new DefaultEntityToEntityMapper(cascadePersist, cascadeUpdate, jpaType, basicUserType, new DefaultEntityLoaderFetchGraphNode(evm, attribute.getName(), (EntityType<?>) managedType, fetchGraph), deleter);
}
} else {
ManagedViewTypeImplementor<?> elementType = (ManagedViewTypeImplementor<?>) type;
jpaType = elementType.getEntityClass();
basicUserType = null;
mutable = elementType.isUpdatable() || elementType.isCreatable() || !persistAllowedSubtypes.isEmpty() || !updateAllowedSubtypes.isEmpty();
Set<ManagedViewType<?>> viewTypes = attribute.getViewTypes();
if (elementType.getJpaManagedType() instanceof EntityType<?> && ownerEntityType instanceof EntityType<?>) {
ExtendedManagedType<?> extendedManagedType = evm.getMetamodel().getEntityMetamodel().getManagedType(ExtendedManagedType.class, elementType.getEntityClass());
entityIdAttributeName = extendedManagedType.getIdAttribute().getName();
attributeIdAttributeName = getAttributeElementIdentifier(evm, (EntityType<?>) ownerEntityType, attribute.getName(), ownerMapping, attribute.getMapping(), extendedManagedType.getType());
}
viewToEntityMapper = createViewToEntityMapper(evm, localCache, updater, attributeIdAttributeName, attribute.getMapping(), attributeLocation, elementType, cascadePersist, cascadeUpdate, readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, elementType, viewTypes, attributeIdAttributeName), owner, ownerMapping);
loadOnlyViewToEntityMapper = createLoadOnlyViewToEntityMapper(attributeLocation, evm, localCache, attributeIdAttributeName, attribute.getMapping(), elementType, cascadePersist, cascadeUpdate, readOnlyAllowedSubtypes, persistAllowedSubtypes, updateAllowedSubtypes, EntityLoaders.referenceLoaderForAttribute(evm, localCache, elementType, viewTypes, attributeIdAttributeName), owner, ownerMapping);
identifiable = viewToEntityMapper.getViewIdAccessor() != null;
}
final boolean shouldJpaMerge = jpaEntity && mutable && cascadeUpdate;
final boolean shouldJpaPersist = jpaEntity && mutable && cascadePersist;
final boolean shouldFlushUpdates = cascadeUpdate && !updateAllowedSubtypes.isEmpty();
final boolean shouldFlushPersists = cascadePersist && !persistAllowedSubtypes.isEmpty();
return new TypeDescriptor(mutable, identifiable, jpaManaged, jpaEntity, shouldJpaMerge, shouldJpaPersist, shouldFlushPersists, shouldFlushUpdates, entityIdAttributeName, attributeIdAttributeName, jpaType, converter, basicUserType, entityToEntityMapper, viewToEntityMapper, loadOnlyViewToEntityMapper);
}
Aggregations