use of io.micronaut.data.model.PersistentEntity in project micronaut-data by micronaut-projects.
the class SqlQueryBuilder method buildInsert.
@NonNull
@Override
public QueryResult buildInsert(AnnotationMetadata repositoryMetadata, PersistentEntity entity) {
boolean escape = shouldEscape(entity);
final String unescapedTableName = getUnescapedTableName(entity);
NamingStrategy namingStrategy = entity.getNamingStrategy();
Collection<? extends PersistentProperty> persistentProperties = entity.getPersistentProperties();
List<QueryParameterBinding> parameterBindings = new ArrayList<>();
List<String> columns = new ArrayList<>();
List<String> values = new ArrayList<>();
for (PersistentProperty prop : persistentProperties) {
if (!prop.isGenerated()) {
traversePersistentProperties(prop, (associations, property) -> {
addWriteExpression(values, prop);
String key = String.valueOf(values.size());
String[] path = asStringPath(associations, property);
parameterBindings.add(new QueryParameterBinding() {
@Override
public String getKey() {
return key;
}
@Override
public DataType getDataType() {
return property.getDataType();
}
@Override
public String[] getPropertyPath() {
return path;
}
});
String columnName = namingStrategy.mappedName(associations, property);
if (escape) {
columnName = quote(columnName);
}
columns.add(columnName);
});
}
}
PersistentProperty version = entity.getVersion();
if (version != null) {
addWriteExpression(values, version);
String key = String.valueOf(values.size());
parameterBindings.add(new QueryParameterBinding() {
@Override
public String getKey() {
return key;
}
@Override
public DataType getDataType() {
return version.getDataType();
}
@Override
public String[] getPropertyPath() {
return new String[] { version.getName() };
}
});
String columnName = namingStrategy.mappedName(Collections.emptyList(), version);
if (escape) {
columnName = quote(columnName);
}
columns.add(columnName);
}
PersistentProperty identity = entity.getIdentity();
if (identity != null) {
traversePersistentProperties(identity, (associations, property) -> {
boolean isSequence = false;
if (isNotForeign(associations)) {
Optional<AnnotationValue<GeneratedValue>> generated = property.findAnnotation(GeneratedValue.class);
if (generated.isPresent()) {
GeneratedValue.Type idGeneratorType = generated.flatMap(av -> av.enumValue(GeneratedValue.Type.class)).orElseGet(() -> selectAutoStrategy(property));
if (idGeneratorType == GeneratedValue.Type.SEQUENCE) {
isSequence = true;
} else if (dialect != Dialect.MYSQL || property.getDataType() != DataType.UUID) {
// Property skipped
return;
}
}
}
if (isSequence) {
values.add(getSequenceStatement(unescapedTableName, property));
} else {
addWriteExpression(values, property);
String key = String.valueOf(values.size());
String[] path = asStringPath(associations, property);
parameterBindings.add(new QueryParameterBinding() {
@Override
public String getKey() {
return key;
}
@Override
public DataType getDataType() {
return property.getDataType();
}
@Override
public String[] getPropertyPath() {
return path;
}
});
}
String columnName = namingStrategy.mappedName(associations, property);
if (escape) {
columnName = quote(columnName);
}
columns.add(columnName);
});
}
String builder = INSERT_INTO + getTableName(entity) + " (" + String.join(",", columns) + CLOSE_BRACKET + " " + "VALUES (" + String.join(String.valueOf(COMMA), values) + CLOSE_BRACKET;
return QueryResult.of(builder, Collections.emptyList(), parameterBindings, Collections.emptyMap());
}
use of io.micronaut.data.model.PersistentEntity in project micronaut-data by micronaut-projects.
the class MongoCollectionsCreator method initialize.
@PostConstruct
void initialize(BeanLocator beanLocator, RuntimeEntityRegistry runtimeEntityRegistry, List<AbstractMongoConfiguration> mongoConfigurations) {
super.initialize(runtimeEntityRegistry, mongoConfigurations, mongoConfiguration -> {
MongoDatabaseFactory mongoDatabaseFactory = getMongoFactory(MongoDatabaseFactory.class, beanLocator, mongoConfiguration);
Map<String, Set<String>> databaseCollections = new HashMap<>();
return new DatabaseOperations<MongoDatabase>() {
@Override
public String getDatabaseName(MongoDatabase database) {
return database.getName();
}
@Override
public MongoDatabase find(PersistentEntity persistentEntity) {
return mongoDatabaseFactory.getDatabase(persistentEntity);
}
@Override
public Set<String> listCollectionNames(MongoDatabase database) {
return databaseCollections.computeIfAbsent(database.getName(), s -> database.listCollectionNames().into(new HashSet<>()));
}
@Override
public void createCollection(MongoDatabase database, String collection) {
database.createCollection(collection);
}
};
});
}
use of io.micronaut.data.model.PersistentEntity in project micronaut-data by micronaut-projects.
the class AbstractMongoCollectionsCreator method initialize.
/**
* Initialize the collections.
*
* @param runtimeEntityRegistry The entity registry
* @param mongoConfigurations The configuration
* @param databaseOperationsProvider The database provider
*/
protected void initialize(RuntimeEntityRegistry runtimeEntityRegistry, List<AbstractMongoConfiguration> mongoConfigurations, DatabaseOperationsProvider<Dtbs> databaseOperationsProvider) {
for (AbstractMongoConfiguration mongoConfiguration : mongoConfigurations) {
// TODO: different initializer per conf
Collection<BeanIntrospection<Object>> introspections = BeanIntrospector.SHARED.findIntrospections(MappedEntity.class);
PersistentEntity[] entities = introspections.stream().filter(i -> !i.getBeanType().getName().contains("$")).filter(i -> !java.lang.reflect.Modifier.isAbstract(i.getBeanType().getModifiers())).map(e -> runtimeEntityRegistry.getEntity(e.getBeanType())).toArray(PersistentEntity[]::new);
DatabaseOperations<Dtbs> databaseOperations = databaseOperationsProvider.get(mongoConfiguration);
for (PersistentEntity entity : entities) {
Dtbs database = databaseOperations.find(entity);
Set<String> collections = databaseOperations.listCollectionNames(database);
String persistedName = entity.getPersistedName();
if (collections.add(persistedName)) {
if (LOG.isInfoEnabled()) {
LOG.info("Creating collection: {} in database: {}", persistedName, databaseOperations.getDatabaseName(database));
}
databaseOperations.createCollection(database, persistedName);
}
for (PersistentProperty persistentProperty : entity.getPersistentProperties()) {
if (persistentProperty instanceof Association) {
Association association = (Association) persistentProperty;
Optional<Association> inverseSide = association.getInverseSide().map(Function.identity());
if (association.getKind() == Relation.Kind.MANY_TO_MANY || association.isForeignKey() && !inverseSide.isPresent()) {
Association owningAssociation = inverseSide.orElse(association);
NamingStrategy namingStrategy = association.getOwner().getNamingStrategy();
String joinCollectionName = namingStrategy.mappedName(owningAssociation);
if (collections.add(joinCollectionName)) {
if (LOG.isInfoEnabled()) {
LOG.info("Creating collection: {} in database: {}", persistedName, databaseOperations.getDatabaseName(database));
}
databaseOperations.createCollection(database, joinCollectionName);
}
}
}
}
}
}
}
use of io.micronaut.data.model.PersistentEntity in project micronaut-data by micronaut-projects.
the class AbstractSqlLikeQueryBuilder method traversePersistentProperties.
private void traversePersistentProperties(List<Association> associations, PersistentProperty property, BiConsumer<List<Association>, PersistentProperty> consumerProperty) {
if (property instanceof Embedded) {
Embedded embedded = (Embedded) property;
PersistentEntity embeddedEntity = embedded.getAssociatedEntity();
Collection<? extends PersistentProperty> embeddedProperties = embeddedEntity.getPersistentProperties();
List<Association> newAssociations = new ArrayList<>(associations);
newAssociations.add((Association) property);
for (PersistentProperty embeddedProperty : embeddedProperties) {
traversePersistentProperties(newAssociations, embeddedProperty, consumerProperty);
}
} else if (property instanceof Association) {
Association association = (Association) property;
if (association.isForeignKey()) {
return;
}
List<Association> newAssociations = new ArrayList<>(associations);
newAssociations.add((Association) property);
PersistentEntity associatedEntity = association.getAssociatedEntity();
PersistentProperty assocIdentity = associatedEntity.getIdentity();
if (assocIdentity == null) {
throw new IllegalStateException("Identity cannot be missing for: " + associatedEntity);
}
if (assocIdentity instanceof Association) {
traversePersistentProperties(newAssociations, assocIdentity, consumerProperty);
} else {
consumerProperty.accept(newAssociations, assocIdentity);
}
} else {
consumerProperty.accept(associations, property);
}
}
use of io.micronaut.data.model.PersistentEntity in project micronaut-data by micronaut-projects.
the class AbstractSqlLikeQueryBuilder method buildUpdate.
@Override
public QueryResult buildUpdate(@NonNull AnnotationMetadata annotationMetadata, @NonNull QueryModel query, @NonNull Map<String, Object> propertiesToUpdate) {
if (propertiesToUpdate.isEmpty()) {
throw new IllegalArgumentException("No properties specified to update");
}
PersistentEntity entity = query.getPersistentEntity();
QueryState queryState = newQueryState(query, false, isAliasForBatch());
StringBuilder queryString = queryState.getQuery();
String tableAlias = queryState.getRootAlias();
String tableName = getTableName(entity);
queryString.append(UPDATE_CLAUSE).append(tableName);
if (tableAlias != null) {
queryString.append(SPACE).append(tableAlias);
}
buildUpdateStatement(queryState, propertiesToUpdate);
buildWhereClause(annotationMetadata, query.getCriteria(), queryState);
return QueryResult.of(queryState.getFinalQuery(), queryState.getQueryParts(), queryState.getParameterBindings(), queryState.getAdditionalRequiredParameters());
}
Aggregations