Skip to content

Commit

Permalink
Polishing.
Browse files Browse the repository at this point in the history
Replace duplicate occurrences of _id with FieldName.ID.name(). Shorten property names to avoid repetative "field" wording. Add Javadoc
to MongoField builder.

See #4464
Original pull request: #4512
  • Loading branch information
mp911de committed Oct 9, 2023
1 parent 691fc05 commit 9c09edd
Show file tree
Hide file tree
Showing 30 changed files with 331 additions and 168 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.dao.DataAccessException;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
import org.springframework.data.mongodb.core.script.NamedMongoScript;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -123,7 +124,8 @@ public boolean exists(String scriptName) {

Assert.hasText(scriptName, "ScriptName must not be null or empty");

return mongoOperations.exists(query(where("_id").is(scriptName)), NamedMongoScript.class, SCRIPT_COLLECTION_NAME);
return mongoOperations.exists(query(where(FieldName.ID.name()).is(scriptName)), NamedMongoScript.class,
SCRIPT_COLLECTION_NAME);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.springframework.data.mongodb.core.convert.MongoJsonSchemaMapper;
import org.springframework.data.mongodb.core.convert.MongoWriter;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.MongoSimpleTypes;
Expand Down Expand Up @@ -79,7 +80,7 @@
*/
class EntityOperations {

private static final String ID_FIELD = "_id";
private static final String ID_FIELD = FieldName.ID.name();

private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> context;
private final QueryMapper queryMapper;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.data.util.StreamUtils;
Expand All @@ -33,7 +34,7 @@
*/
public class MappedDocument {

private static final String ID_FIELD = "_id";
private static final String ID_FIELD = FieldName.ID.name();
private static final Document ID_ONLY_PROJECTION = new Document(ID_FIELD, 1);

private final Document document;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.convert.QueryMapper;
import org.springframework.data.mongodb.core.convert.UpdateMapper;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.mapping.MongoId;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
Expand Down Expand Up @@ -849,7 +850,7 @@ private boolean shardedById(MongoPersistentEntity<?> domainType) {
}

String key = shardKey.getPropertyNames().iterator().next();
if ("_id".equals(key)) {
if (FieldName.ID.name().equals(key)) {
return true;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import static org.springframework.data.mongodb.core.query.SerializationUtils.*;

import org.springframework.data.mongodb.core.CollectionPreparerSupport.CollectionPreparerDelegate;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.util.function.Tuple2;
Expand Down Expand Up @@ -104,6 +103,7 @@
import org.springframework.data.mongodb.core.index.MongoMappingEventPublisher;
import org.springframework.data.mongodb.core.index.ReactiveIndexOperations;
import org.springframework.data.mongodb.core.index.ReactiveMongoPersistentEntityIndexCreator;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
Expand Down Expand Up @@ -133,7 +133,16 @@
import com.mongodb.MongoException;
import com.mongodb.ReadPreference;
import com.mongodb.WriteConcern;
import com.mongodb.client.model.*;
import com.mongodb.client.model.CountOptions;
import com.mongodb.client.model.CreateCollectionOptions;
import com.mongodb.client.model.CreateViewOptions;
import com.mongodb.client.model.DeleteOptions;
import com.mongodb.client.model.EstimatedDocumentCountOptions;
import com.mongodb.client.model.FindOneAndDeleteOptions;
import com.mongodb.client.model.FindOneAndReplaceOptions;
import com.mongodb.client.model.FindOneAndUpdateOptions;
import com.mongodb.client.model.ReturnDocument;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.changestream.FullDocument;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertOneResult;
Expand Down Expand Up @@ -826,7 +835,7 @@ public Mono<Boolean> exists(Query query, @Nullable Class<?> entityClass, String
Document filter = queryContext.getMappedQuery(entityClass, this::getPersistentEntity);

FindPublisher<Document> findPublisher = collectionPreparer.prepare(collection).find(filter, Document.class)
.projection(new Document("_id", 1));
.projection(new Document(FieldName.ID.name(), 1));

if (LOGGER.isDebugEnabled()) {
LOGGER.debug(String.format("exists: %s in collection: %s", serializeToJsonSafely(filter), collectionName));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
import org.springframework.data.mongodb.core.aggregation.MergeOperation.MergeOperationBuilder;
import org.springframework.data.mongodb.core.aggregation.ReplaceRootOperation.ReplaceRootDocumentOperationBuilder;
import org.springframework.data.mongodb.core.aggregation.ReplaceRootOperation.ReplaceRootOperationBuilder;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
import org.springframework.data.mongodb.core.query.NearQuery;
Expand Down Expand Up @@ -224,7 +225,7 @@ public AggregationOptions getOptions() {
* @return
*/
public static String previousOperation() {
return "_id";
return FieldName.ID.name();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.util.List;
import java.util.Map;

import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
Expand All @@ -40,7 +41,7 @@ public final class Fields implements Iterable<Field> {
private static final String AMBIGUOUS_EXCEPTION = "Found two fields both using '%s' as name: %s and %s; Please "
+ "customize your field definitions to get to unique field names";

public static final String UNDERSCORE_ID = "_id";
public static final String UNDERSCORE_ID = FieldName.ID.name();
public static final String UNDERSCORE_ID_REF = "$_id";

private final List<Field> fields;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bson.Document;

import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.MongoDatabaseUtils;
import org.springframework.data.mongodb.core.convert.ReferenceLoader.DocumentReferenceQuery;
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -87,7 +87,8 @@ public Object resolveDbRef(MongoPersistentProperty property, @Nullable DBRef dbr

@Override
public Document fetch(DBRef dbRef) {
return getReferenceLoader().fetchOne(DocumentReferenceQuery.forSingleDocument(Filters.eq("_id", dbRef.getId())),
return getReferenceLoader().fetchOne(
DocumentReferenceQuery.forSingleDocument(Filters.eq(FieldName.ID.name(), dbRef.getId())),
ReferenceCollection.fromDBRef(dbRef));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public void put(MongoPersistentProperty prop, @Nullable Object value) {

Assert.notNull(prop, "MongoPersistentProperty must not be null");

Iterator<String> parts = Arrays.asList(prop.getMongoField().getFieldName().parts()).iterator();
Iterator<String> parts = Arrays.asList(prop.getMongoField().getName().parts()).iterator();
Bson document = this.document;

while (parts.hasNext()) {
Expand Down Expand Up @@ -129,7 +129,7 @@ public Object get(MongoPersistentProperty property) {
*/
@Nullable
public Object getRawId(MongoPersistentEntity<?> entity) {
return entity.hasIdProperty() ? get(entity.getRequiredIdProperty()) : BsonUtils.get(document, "_id");
return entity.hasIdProperty() ? get(entity.getRequiredIdProperty()) : BsonUtils.get(document, FieldName.ID.name());
}

/**
Expand All @@ -148,7 +148,7 @@ public boolean hasValue(MongoPersistentProperty property) {
}

FieldName getFieldName(MongoPersistentProperty prop) {
return prop.getMongoField().getFieldName();
return prop.getMongoField().getName();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mapping.model.BeanWrapperPropertyAccessorFactory;
import org.springframework.data.mongodb.core.mapping.DocumentPointer;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;

Expand Down Expand Up @@ -232,7 +233,7 @@ Object updatePlaceholders(org.bson.Document source, org.bson.Document target,
attribute = attribute.substring(attribute.lastIndexOf('.') + 1);
}

String fieldName = entry.getKey().equals("_id") ? "id" : entry.getKey();
String fieldName = entry.getKey().equals(FieldName.ID.name()) ? "id" : entry.getKey();
if (!fieldName.contains(".")) {

Object targetValue = propertyAccessor.getProperty(persistentEntity.getPersistentProperty(fieldName));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,8 +231,8 @@ public CustomConversions getCustomConversions() {
}

/**
* Configure the characters dots potentially contained in a {@link Map} shall be replaced with. By default we don't do
* any translation but rather reject a {@link Map} with keys containing dots causing the conversion for the entire
* Configure the characters dots potentially contained in a {@link Map} shall be replaced with. By default, we don't
* do any translation but rather reject a {@link Map} with keys containing dots causing the conversion for the entire
* object to fail. If further customization of the translation is needed, have a look at
* {@link #potentiallyEscapeMapKey(String)} as well as {@link #potentiallyUnescapeMapKey(String)}.
* <p>
Expand All @@ -246,7 +246,8 @@ public void setMapKeyDotReplacement(@Nullable String mapKeyDotReplacement) {
}

/**
* If {@link #preserveMapKeys(boolean) preserve} is set to {@literal true} the conversion will treat map keys containing {@literal .} (dot) characters as is.
* If {@link #preserveMapKeys(boolean) preserve} is set to {@literal true} the conversion will treat map keys
* containing dot ({@literal .}) characters as is.
*
* @since 4.2
* @see #setMapKeyDotReplacement(String)
Expand Down Expand Up @@ -357,7 +358,7 @@ private <R> R doReadProjection(ConversionContext context, Bson bson, EntityProje
DocumentAccessor documentAccessor = new DocumentAccessor(bson) {
@Override
FieldName getFieldName(MongoPersistentProperty prop) {
return propertyTranslator.translate(prop).getMongoField().getFieldName();
return propertyTranslator.translate(prop).getMongoField().getName();
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.data.convert.ReadingConverter;
import org.springframework.data.convert.WritingConverter;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.query.Term;
import org.springframework.data.mongodb.core.script.NamedMongoScript;
import org.springframework.util.Assert;
Expand Down Expand Up @@ -300,7 +301,7 @@ public NamedMongoScript convert(Document source) {
return null;
}

String id = source.get("_id").toString();
String id = source.get(FieldName.ID.name()).toString();
Object rawValue = source.get("value");

return new NamedMongoScript(id, ((Code) rawValue).getCode());
Expand All @@ -320,7 +321,7 @@ public Document convert(NamedMongoScript source) {

Document document = new Document();

document.put("_id", source.getName());
document.put(FieldName.ID.name(), source.getName());
document.put("value", new Code(source.getCode()));

return document;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
import org.springframework.data.mapping.PropertyHandler;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.query.MongoRegexCreator;
Expand Down Expand Up @@ -278,7 +279,8 @@ private Set<Class<?>> getTypesToMatch(Example<?> example) {
}

private static boolean isEmptyIdProperty(Entry<String, Object> entry) {
return entry.getKey().equals("_id") && (entry.getValue() == null || entry.getValue().equals(Optional.empty()));
return entry.getKey().equals(FieldName.ID.name())
&& (entry.getValue() == null || entry.getValue().equals(Optional.empty()));
}

private static void applyStringMatcher(Map.Entry<String, Object> entry, StringMatcher stringMatcher,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
import org.springframework.data.mongodb.core.aggregation.AggregationExpression;
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter.NestedDocument;
import org.springframework.data.mongodb.core.mapping.FieldName.Type;
import org.springframework.data.mongodb.core.mapping.FieldName;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty.PropertyToFieldNameConverter;
Expand Down Expand Up @@ -81,7 +81,7 @@ public class QueryMapper {

protected static final Log LOGGER = LogFactory.getLog(QueryMapper.class);

private static final List<String> DEFAULT_ID_NAMES = Arrays.asList("id", "_id");
private static final List<String> DEFAULT_ID_NAMES = Arrays.asList("id", FieldName.ID.name());
private static final Document META_TEXT_SCORE = new Document("$meta", "textScore");
static final TypeInformation<?> NESTED_DOCUMENT = TypeInformation.of(NestedDocument.class);

Expand Down Expand Up @@ -367,7 +367,7 @@ protected Field createPropertyField(@Nullable MongoPersistentEntity<?> entity, S
return new Field(key);
}

if (Field.ID_KEY.equals(key)) {
if (FieldName.ID.name().equals(key)) {
return new MetadataBackedField(key, entity, mappingContext, entity.getIdProperty());
}

Expand All @@ -387,8 +387,7 @@ protected Document getMappedKeyword(Keyword keyword, @Nullable MongoPersistentEn
if (keyword.isOrOrNor() || (keyword.hasIterableValue() && !keyword.isGeometry())) {

Iterable<?> conditions = keyword.getValue();
List<Object> newConditions = conditions instanceof Collection<?> collection
? new ArrayList<>(collection.size())
List<Object> newConditions = conditions instanceof Collection<?> collection ? new ArrayList<>(collection.size())
: new ArrayList<>();

for (Object condition : conditions) {
Expand Down Expand Up @@ -624,7 +623,7 @@ protected Object convertSimpleOrDocument(Object source, @Nullable MongoPersisten

String key = ObjectUtils.nullSafeToString(converter.convertToMongoType(it.getKey()));

if (it.getValue() instanceof Document document) {
if (it.getValue()instanceof Document document) {
map.put(key, getMappedObject(document, entity));
} else {
map.put(key, delegateConvertToMongoType(it.getValue(), entity));
Expand Down Expand Up @@ -977,8 +976,6 @@ protected static class Field {

protected static final Pattern POSITIONAL_OPERATOR = Pattern.compile("\\$\\[.*\\]");

private static final String ID_KEY = "_id";

protected final String name;

/**
Expand Down Expand Up @@ -1008,7 +1005,7 @@ public Field with(String name) {
* @return
*/
public boolean isIdField() {
return ID_KEY.equals(name);
return FieldName.ID.name().equals(name);
}

/**
Expand Down Expand Up @@ -1053,7 +1050,7 @@ public boolean isAssociation() {
* @return
*/
public String getMappedKey() {
return isIdField() ? ID_KEY : name;
return isIdField() ? FieldName.ID.name() : name;
}

/**
Expand Down Expand Up @@ -1222,9 +1219,11 @@ public Class<?> getFieldType() {

@Override
public String getMappedKey() {
if(getProperty() != null && getProperty().getMongoField().getFieldName().isOfType(Type.KEY)) {

if (getProperty() != null && getProperty().getMongoField().getName().isKey()) {
return getProperty().getFieldName();
}

return path == null ? name : path.toDotPath(isAssociation() ? getAssociationConverter() : getPropertyConverter());
}

Expand Down Expand Up @@ -1355,7 +1354,7 @@ private static String resolvePath(String source) {

/* always start from a property, so we can skip the first segment.
from there remove any position placeholder */
for(int i=1; i < segments.length; i++) {
for (int i = 1; i < segments.length; i++) {
String segment = segments[i];
if (segment.startsWith("[") && segment.endsWith("]")) {
continue;
Expand Down
Loading

0 comments on commit 9c09edd

Please sign in to comment.