use of io.micronaut.data.model.runtime.RuntimePersistentEntity in project micronaut-data by micronaut-projects.
the class DefaultJdbcRepositoryOperations method updateAll.
@NonNull
@Override
public <T> Iterable<T> updateAll(@NonNull UpdateBatchOperation<T> operation) {
return executeWrite(connection -> {
final AnnotationMetadata annotationMetadata = operation.getAnnotationMetadata();
final Class<?> repositoryType = operation.getRepositoryType();
SqlQueryBuilder queryBuilder = queryBuilders.getOrDefault(repositoryType, DEFAULT_SQL_BUILDER);
final RuntimePersistentEntity<T> persistentEntity = getEntity(operation.getRootEntity());
DBOperation dbOperation = new StoredQuerySqlOperation(queryBuilder, operation.getStoredQuery());
JdbcOperationContext ctx = new JdbcOperationContext(annotationMetadata, repositoryType, queryBuilder.dialect(), connection);
if (!isSupportsBatchUpdate(persistentEntity, queryBuilder.dialect())) {
return operation.split().stream().map(updateOp -> {
JdbcEntityOperations<T> op = new JdbcEntityOperations<>(ctx, persistentEntity, updateOp.getEntity(), dbOperation);
op.update();
return op.getEntity();
}).collect(Collectors.toList());
}
JdbcEntitiesOperations<T> op = new JdbcEntitiesOperations<>(ctx, persistentEntity, operation, dbOperation);
op.update();
return op.getEntities();
});
}
use of io.micronaut.data.model.runtime.RuntimePersistentEntity in project micronaut-data by micronaut-projects.
the class EventIntegrator method integrate.
@Override
public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
EventListenerRegistry eventListenerRegistry = serviceRegistry.getService(EventListenerRegistry.class);
final EntityEventListener<Object> entityEventListener = entityRegistry.getEntityEventListener();
eventListenerRegistry.getEventListenerGroup(EventType.PRE_INSERT).appendListener((PreInsertEventListener) event -> {
Class mappedClass = event.getPersister().getMappedClass();
if (isNotSupportedMappedClass(mappedClass)) {
return false;
}
final RuntimePersistentEntity<Object> entity = entityRegistry.getEntity(mappedClass);
if (entity.hasPrePersistEventListeners()) {
Object[] state = event.getState();
final DefaultEntityEventContext<Object> context = new StatefulHibernateEventContext<>(entity, event, state);
return !entityEventListener.prePersist(context);
}
return false;
});
eventListenerRegistry.getEventListenerGroup(EventType.POST_INSERT).appendListener(new PostInsertEventListener() {
@Override
public void onPostInsert(PostInsertEvent event) {
Class mappedClass = event.getPersister().getMappedClass();
if (isNotSupportedMappedClass(mappedClass)) {
return;
}
final RuntimePersistentEntity<Object> entity = entityRegistry.getEntity(mappedClass);
if (entity.hasPostPersistEventListeners()) {
final DefaultEntityEventContext<Object> context = new SimpleHibernateEventContext<>(entity, event.getEntity());
entityEventListener.postPersist(context);
}
}
@Override
public boolean requiresPostCommitHanding(EntityPersister persister) {
return false;
}
});
eventListenerRegistry.getEventListenerGroup(EventType.PRE_DELETE).appendListener((PreDeleteEventListener) event -> {
Class mappedClass = event.getPersister().getMappedClass();
if (isNotSupportedMappedClass(mappedClass)) {
return false;
}
final RuntimePersistentEntity<Object> entity = entityRegistry.getEntity(mappedClass);
if (entity.hasPreRemoveEventListeners()) {
Object[] state = event.getDeletedState();
final DefaultEntityEventContext<Object> context = new StatefulHibernateEventContext<>(entity, event, state);
return !entityEventListener.preRemove(context);
}
return false;
});
eventListenerRegistry.getEventListenerGroup(EventType.POST_DELETE).appendListener(new PostDeleteEventListener() {
@Override
public boolean requiresPostCommitHanding(EntityPersister persister) {
return false;
}
@Override
public void onPostDelete(PostDeleteEvent event) {
Class mappedClass = event.getPersister().getMappedClass();
if (isNotSupportedMappedClass(mappedClass)) {
return;
}
final RuntimePersistentEntity<Object> entity = entityRegistry.getEntity(mappedClass);
if (entity.hasPostPersistEventListeners()) {
final DefaultEntityEventContext<Object> context = new SimpleHibernateEventContext<>(entity, event.getEntity());
entityEventListener.postRemove(context);
}
}
});
eventListenerRegistry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener((PreUpdateEventListener) event -> {
Class mappedClass = event.getPersister().getMappedClass();
if (isNotSupportedMappedClass(mappedClass)) {
return false;
}
final RuntimePersistentEntity<Object> entity = entityRegistry.getEntity(mappedClass);
if (entity.hasPreUpdateEventListeners()) {
Object[] state = event.getState();
final DefaultEntityEventContext<Object> context = new StatefulHibernateEventContext<>(entity, event, state);
return !entityEventListener.preUpdate(context);
}
return false;
});
eventListenerRegistry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(new PostUpdateEventListener() {
@Override
public boolean requiresPostCommitHanding(EntityPersister persister) {
return false;
}
@Override
public void onPostUpdate(PostUpdateEvent event) {
Class mappedClass = event.getPersister().getMappedClass();
if (isNotSupportedMappedClass(mappedClass)) {
return;
}
final RuntimePersistentEntity<Object> entity = entityRegistry.getEntity(mappedClass);
if (entity.hasPostPersistEventListeners()) {
final DefaultEntityEventContext<Object> context = new SimpleHibernateEventContext<>(entity, event.getEntity());
entityEventListener.postUpdate(context);
}
}
});
eventListenerRegistry.getEventListenerGroup(EventType.POST_LOAD).appendListener((PostLoadEventListener) event -> {
Class mappedClass = event.getPersister().getMappedClass();
if (isNotSupportedMappedClass(mappedClass)) {
return;
}
final RuntimePersistentEntity<Object> entity = entityRegistry.getEntity(mappedClass);
if (entity.hasPreUpdateEventListeners()) {
final DefaultEntityEventContext<Object> context = new SimpleHibernateEventContext<>(entity, event.getEntity());
entityEventListener.postLoad(context);
}
});
}
use of io.micronaut.data.model.runtime.RuntimePersistentEntity in project micronaut-data by micronaut-projects.
the class HibernateJpaOperations method bindParameters.
private <T, R> void bindParameters(Query<?> q, @NonNull PreparedQuery<T, R> preparedQuery, String query) {
for (QueryParameterBinding queryParameterBinding : preparedQuery.getQueryBindings()) {
String parameterName = Objects.requireNonNull(queryParameterBinding.getName(), "Parameter name cannot be null!");
Object value;
if (queryParameterBinding.getParameterIndex() != -1) {
value = resolveParameterValue(queryParameterBinding, preparedQuery.getParameterArray());
} else if (queryParameterBinding.isAutoPopulated()) {
String[] propertyPath = queryParameterBinding.getRequiredPropertyPath();
RuntimePersistentEntity<T> persistentEntity = getEntity(preparedQuery.getRootEntity());
PersistentPropertyPath pp = persistentEntity.getPropertyPath(propertyPath);
if (pp == null) {
throw new IllegalStateException("Cannot find auto populated property: " + String.join(".", propertyPath));
}
RuntimePersistentProperty<?> persistentProperty = (RuntimePersistentProperty) pp.getProperty();
Object previousValue = null;
QueryParameterBinding previousPopulatedValueParameter = queryParameterBinding.getPreviousPopulatedValueParameter();
if (previousPopulatedValueParameter != null) {
if (previousPopulatedValueParameter.getParameterIndex() == -1) {
throw new IllegalStateException("Previous value parameter cannot be bind!");
}
previousValue = resolveParameterValue(previousPopulatedValueParameter, preparedQuery.getParameterArray());
}
value = runtimeEntityRegistry.autoPopulateRuntimeProperty(persistentProperty, previousValue);
} else {
throw new IllegalStateException("Invalid query [" + query + "]. Unable to establish parameter value for parameter at name: " + parameterName);
}
if (preparedQuery.isNative()) {
int parameterIndex = queryParameterBinding.getParameterIndex();
Argument<?> argument = preparedQuery.getArguments()[parameterIndex];
Class<?> argumentType = argument.getType();
if (Collection.class.isAssignableFrom(argumentType)) {
Type valueType = sessionFactory.getTypeHelper().heuristicType(argument.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT).getType().getName());
if (valueType != null) {
q.setParameterList(parameterName, value == null ? Collections.emptyList() : (Collection<?>) value, valueType);
continue;
}
} else if (Object[].class.isAssignableFrom(argumentType)) {
q.setParameterList(parameterName, value == null ? ArrayUtils.EMPTY_OBJECT_ARRAY : (Object[]) value);
continue;
} else if (value == null) {
Type type = sessionFactory.getTypeHelper().heuristicType(argumentType.getName());
if (type != null) {
q.setParameter(parameterName, null, type);
continue;
}
}
}
q.setParameter(parameterName, value);
}
}
use of io.micronaut.data.model.runtime.RuntimePersistentEntity in project micronaut-data by micronaut-projects.
the class DefaultMongoRepositoryOperations method triggerPostLoad.
private <K> K triggerPostLoad(AnnotationMetadata annotationMetadata, RuntimePersistentEntity<K> persistentEntity, K entity) {
if (persistentEntity.hasPostLoadEventListeners()) {
entity = triggerPostLoad(entity, persistentEntity, annotationMetadata);
}
for (PersistentProperty pp : persistentEntity.getPersistentProperties()) {
if (pp instanceof RuntimeAssociation) {
RuntimeAssociation runtimeAssociation = (RuntimeAssociation) pp;
Object o = runtimeAssociation.getProperty().get(entity);
if (o == null) {
continue;
}
RuntimePersistentEntity associatedEntity = runtimeAssociation.getAssociatedEntity();
switch(runtimeAssociation.getKind()) {
case MANY_TO_MANY:
case ONE_TO_MANY:
if (o instanceof Iterable) {
for (Object value : ((Iterable) o)) {
triggerPostLoad(value, associatedEntity, annotationMetadata);
}
}
continue;
case MANY_TO_ONE:
case ONE_TO_ONE:
case EMBEDDED:
triggerPostLoad(o, associatedEntity, annotationMetadata);
continue;
default:
throw new IllegalStateException("Unknown kind: " + runtimeAssociation.getKind());
}
}
}
return entity;
}
use of io.micronaut.data.model.runtime.RuntimePersistentEntity in project micronaut-data by micronaut-projects.
the class DefaultMongoRepositoryOperations method createMongoDeleteManyOperation.
private <T> MongoEntitiesOperation<T> createMongoDeleteManyOperation(MongoOperationContext ctx, RuntimePersistentEntity<T> persistentEntity, Iterable<T> entities) {
return new MongoEntitiesOperation<T>(ctx, persistentEntity, entities, false) {
final MongoDatabase mongoDatabase = getDatabase(persistentEntity, ctx.repositoryType);
final MongoCollection<T> collection = getCollection(mongoDatabase, persistentEntity, persistentEntity.getIntrospection().getBeanType());
Map<Data, Bson> filters;
@Override
protected void collectAutoPopulatedPreviousValues() {
filters = entities.stream().collect(Collectors.toMap(d -> d, d -> MongoUtils.filterByIdAndVersion(conversionService, persistentEntity, d.entity, collection.getCodecRegistry())));
}
@Override
protected void execute() throws RuntimeException {
List<Bson> filters = entities.stream().filter(d -> !d.vetoed).map(d -> this.filters.get(d)).collect(Collectors.toList());
if (!filters.isEmpty()) {
Bson filter = Filters.or(filters);
if (QUERY_LOG.isDebugEnabled()) {
QUERY_LOG.debug("Executing Mongo 'deleteMany' with filter: {}", filter.toBsonDocument().toJson());
}
DeleteResult deleteResult = collection.deleteMany(ctx.clientSession, filter);
modifiedCount = deleteResult.getDeletedCount();
}
if (persistentEntity.getVersion() != null) {
int expected = (int) entities.stream().filter(d -> !d.vetoed).count();
checkOptimisticLocking(expected, (int) modifiedCount);
}
}
};
}
Aggregations