Skip to content

Commit 9c09edd

Browse files
committed
Polishing.
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
1 parent 691fc05 commit 9c09edd

30 files changed

+331
-168
lines changed

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultScriptOperations.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
import org.bson.Document;
3030
import org.bson.types.ObjectId;
3131
import org.springframework.dao.DataAccessException;
32+
import org.springframework.data.mongodb.core.mapping.FieldName;
3233
import org.springframework.data.mongodb.core.script.ExecutableMongoScript;
3334
import org.springframework.data.mongodb.core.script.NamedMongoScript;
3435
import org.springframework.util.Assert;
@@ -123,7 +124,8 @@ public boolean exists(String scriptName) {
123124

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

126-
return mongoOperations.exists(query(where("_id").is(scriptName)), NamedMongoScript.class, SCRIPT_COLLECTION_NAME);
127+
return mongoOperations.exists(query(where(FieldName.ID.name()).is(scriptName)), NamedMongoScript.class,
128+
SCRIPT_COLLECTION_NAME);
127129
}
128130

129131
@Override

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/EntityOperations.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
import org.springframework.data.mongodb.core.convert.MongoJsonSchemaMapper;
4040
import org.springframework.data.mongodb.core.convert.MongoWriter;
4141
import org.springframework.data.mongodb.core.convert.QueryMapper;
42+
import org.springframework.data.mongodb.core.mapping.FieldName;
4243
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
4344
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
4445
import org.springframework.data.mongodb.core.mapping.MongoSimpleTypes;
@@ -79,7 +80,7 @@
7980
*/
8081
class EntityOperations {
8182

82-
private static final String ID_FIELD = "_id";
83+
private static final String ID_FIELD = FieldName.ID.name();
8384

8485
private final MappingContext<? extends MongoPersistentEntity<?>, MongoPersistentProperty> context;
8586
private final QueryMapper queryMapper;

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MappedDocument.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020

2121
import org.bson.Document;
2222
import org.bson.conversions.Bson;
23+
import org.springframework.data.mongodb.core.mapping.FieldName;
2324
import org.springframework.data.mongodb.core.query.Update;
2425
import org.springframework.data.mongodb.core.query.UpdateDefinition;
2526
import org.springframework.data.util.StreamUtils;
@@ -33,7 +34,7 @@
3334
*/
3435
public class MappedDocument {
3536

36-
private static final String ID_FIELD = "_id";
37+
private static final String ID_FIELD = FieldName.ID.name();
3738
private static final Document ID_ONLY_PROJECTION = new Document(ID_FIELD, 1);
3839

3940
private final Document document;

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/QueryOperations.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
4949
import org.springframework.data.mongodb.core.convert.QueryMapper;
5050
import org.springframework.data.mongodb.core.convert.UpdateMapper;
51+
import org.springframework.data.mongodb.core.mapping.FieldName;
5152
import org.springframework.data.mongodb.core.mapping.MongoId;
5253
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
5354
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
@@ -849,7 +850,7 @@ private boolean shardedById(MongoPersistentEntity<?> domainType) {
849850
}
850851

851852
String key = shardKey.getPropertyNames().iterator().next();
852-
if ("_id".equals(key)) {
853+
if (FieldName.ID.name().equals(key)) {
853854
return true;
854855
}
855856

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java

+12-3
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717

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

20-
import org.springframework.data.mongodb.core.CollectionPreparerSupport.CollectionPreparerDelegate;
2120
import reactor.core.publisher.Flux;
2221
import reactor.core.publisher.Mono;
2322
import reactor.util.function.Tuple2;
@@ -104,6 +103,7 @@
104103
import org.springframework.data.mongodb.core.index.MongoMappingEventPublisher;
105104
import org.springframework.data.mongodb.core.index.ReactiveIndexOperations;
106105
import org.springframework.data.mongodb.core.index.ReactiveMongoPersistentEntityIndexCreator;
106+
import org.springframework.data.mongodb.core.mapping.FieldName;
107107
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
108108
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
109109
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
@@ -133,7 +133,16 @@
133133
import com.mongodb.MongoException;
134134
import com.mongodb.ReadPreference;
135135
import com.mongodb.WriteConcern;
136-
import com.mongodb.client.model.*;
136+
import com.mongodb.client.model.CountOptions;
137+
import com.mongodb.client.model.CreateCollectionOptions;
138+
import com.mongodb.client.model.CreateViewOptions;
139+
import com.mongodb.client.model.DeleteOptions;
140+
import com.mongodb.client.model.EstimatedDocumentCountOptions;
141+
import com.mongodb.client.model.FindOneAndDeleteOptions;
142+
import com.mongodb.client.model.FindOneAndReplaceOptions;
143+
import com.mongodb.client.model.FindOneAndUpdateOptions;
144+
import com.mongodb.client.model.ReturnDocument;
145+
import com.mongodb.client.model.UpdateOptions;
137146
import com.mongodb.client.model.changestream.FullDocument;
138147
import com.mongodb.client.result.DeleteResult;
139148
import com.mongodb.client.result.InsertOneResult;
@@ -826,7 +835,7 @@ public Mono<Boolean> exists(Query query, @Nullable Class<?> entityClass, String
826835
Document filter = queryContext.getMappedQuery(entityClass, this::getPersistentEntity);
827836

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

831840
if (LOGGER.isDebugEnabled()) {
832841
LOGGER.debug(String.format("exists: %s in collection: %s", serializeToJsonSafely(filter), collectionName));

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
import org.springframework.data.mongodb.core.aggregation.MergeOperation.MergeOperationBuilder;
3333
import org.springframework.data.mongodb.core.aggregation.ReplaceRootOperation.ReplaceRootDocumentOperationBuilder;
3434
import org.springframework.data.mongodb.core.aggregation.ReplaceRootOperation.ReplaceRootOperationBuilder;
35+
import org.springframework.data.mongodb.core.mapping.FieldName;
3536
import org.springframework.data.mongodb.core.query.Criteria;
3637
import org.springframework.data.mongodb.core.query.CriteriaDefinition;
3738
import org.springframework.data.mongodb.core.query.NearQuery;
@@ -224,7 +225,7 @@ public AggregationOptions getOptions() {
224225
* @return
225226
*/
226227
public static String previousOperation() {
227-
return "_id";
228+
return FieldName.ID.name();
228229
}
229230

230231
/**

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Fields.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import java.util.List;
2424
import java.util.Map;
2525

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

43-
public static final String UNDERSCORE_ID = "_id";
44+
public static final String UNDERSCORE_ID = FieldName.ID.name();
4445
public static final String UNDERSCORE_ID_REF = "$_id";
4546

4647
private final List<Field> fields;

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -25,12 +25,12 @@
2525
import org.apache.commons.logging.Log;
2626
import org.apache.commons.logging.LogFactory;
2727
import org.bson.Document;
28-
2928
import org.springframework.dao.InvalidDataAccessApiUsageException;
3029
import org.springframework.data.mongodb.MongoDatabaseFactory;
3130
import org.springframework.data.mongodb.MongoDatabaseUtils;
3231
import org.springframework.data.mongodb.core.convert.ReferenceLoader.DocumentReferenceQuery;
3332
import org.springframework.data.mongodb.core.mapping.BasicMongoPersistentProperty;
33+
import org.springframework.data.mongodb.core.mapping.FieldName;
3434
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
3535
import org.springframework.lang.Nullable;
3636
import org.springframework.util.Assert;
@@ -87,7 +87,8 @@ public Object resolveDbRef(MongoPersistentProperty property, @Nullable DBRef dbr
8787

8888
@Override
8989
public Document fetch(DBRef dbRef) {
90-
return getReferenceLoader().fetchOne(DocumentReferenceQuery.forSingleDocument(Filters.eq("_id", dbRef.getId())),
90+
return getReferenceLoader().fetchOne(
91+
DocumentReferenceQuery.forSingleDocument(Filters.eq(FieldName.ID.name(), dbRef.getId())),
9192
ReferenceCollection.fromDBRef(dbRef));
9293
}
9394

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentAccessor.java

+3-3
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ public void put(MongoPersistentProperty prop, @Nullable Object value) {
9292

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

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

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

135135
/**
@@ -148,7 +148,7 @@ public boolean hasValue(MongoPersistentProperty property) {
148148
}
149149

150150
FieldName getFieldName(MongoPersistentProperty prop) {
151-
return prop.getMongoField().getFieldName();
151+
return prop.getMongoField().getName();
152152
}
153153

154154
/**

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentPointerFactory.java

+2-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.springframework.data.mapping.context.MappingContext;
3535
import org.springframework.data.mapping.model.BeanWrapperPropertyAccessorFactory;
3636
import org.springframework.data.mongodb.core.mapping.DocumentPointer;
37+
import org.springframework.data.mongodb.core.mapping.FieldName;
3738
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
3839
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
3940

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

235-
String fieldName = entry.getKey().equals("_id") ? "id" : entry.getKey();
236+
String fieldName = entry.getKey().equals(FieldName.ID.name()) ? "id" : entry.getKey();
236237
if (!fieldName.contains(".")) {
237238

238239
Object targetValue = propertyAccessor.getProperty(persistentEntity.getPersistentProperty(fieldName));

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java

+5-4
Original file line numberDiff line numberDiff line change
@@ -231,8 +231,8 @@ public CustomConversions getCustomConversions() {
231231
}
232232

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

248248
/**
249-
* If {@link #preserveMapKeys(boolean) preserve} is set to {@literal true} the conversion will treat map keys containing {@literal .} (dot) characters as is.
249+
* If {@link #preserveMapKeys(boolean) preserve} is set to {@literal true} the conversion will treat map keys
250+
* containing dot ({@literal .}) characters as is.
250251
*
251252
* @since 4.2
252253
* @see #setMapKeyDotReplacement(String)
@@ -357,7 +358,7 @@ private <R> R doReadProjection(ConversionContext context, Bson bson, EntityProje
357358
DocumentAccessor documentAccessor = new DocumentAccessor(bson) {
358359
@Override
359360
FieldName getFieldName(MongoPersistentProperty prop) {
360-
return propertyTranslator.translate(prop).getMongoField().getFieldName();
361+
return propertyTranslator.translate(prop).getMongoField().getName();
361362
}
362363
};
363364

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverters.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
import org.springframework.core.convert.converter.ConverterFactory;
5252
import org.springframework.data.convert.ReadingConverter;
5353
import org.springframework.data.convert.WritingConverter;
54+
import org.springframework.data.mongodb.core.mapping.FieldName;
5455
import org.springframework.data.mongodb.core.query.Term;
5556
import org.springframework.data.mongodb.core.script.NamedMongoScript;
5657
import org.springframework.util.Assert;
@@ -300,7 +301,7 @@ public NamedMongoScript convert(Document source) {
300301
return null;
301302
}
302303

303-
String id = source.get("_id").toString();
304+
String id = source.get(FieldName.ID.name()).toString();
304305
Object rawValue = source.get("value");
305306

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

321322
Document document = new Document();
322323

323-
document.put("_id", source.getName());
324+
document.put(FieldName.ID.name(), source.getName());
324325
document.put("value", new Code(source.getCode()));
325326

326327
return document;

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoExampleMapper.java

+3-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.springframework.data.domain.ExampleMatcher.StringMatcher;
3535
import org.springframework.data.mapping.PropertyHandler;
3636
import org.springframework.data.mapping.context.MappingContext;
37+
import org.springframework.data.mongodb.core.mapping.FieldName;
3738
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
3839
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
3940
import org.springframework.data.mongodb.core.query.MongoRegexCreator;
@@ -278,7 +279,8 @@ private Set<Class<?>> getTypesToMatch(Example<?> example) {
278279
}
279280

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

284286
private static void applyStringMatcher(Map.Entry<String, Object> entry, StringMatcher stringMatcher,

spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java

+11-12
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@
4747
import org.springframework.data.mongodb.core.aggregation.AggregationExpression;
4848
import org.springframework.data.mongodb.core.aggregation.RelaxedTypeBasedAggregationOperationContext;
4949
import org.springframework.data.mongodb.core.convert.MappingMongoConverter.NestedDocument;
50-
import org.springframework.data.mongodb.core.mapping.FieldName.Type;
50+
import org.springframework.data.mongodb.core.mapping.FieldName;
5151
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
5252
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty;
5353
import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty.PropertyToFieldNameConverter;
@@ -81,7 +81,7 @@ public class QueryMapper {
8181

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

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

@@ -367,7 +367,7 @@ protected Field createPropertyField(@Nullable MongoPersistentEntity<?> entity, S
367367
return new Field(key);
368368
}
369369

370-
if (Field.ID_KEY.equals(key)) {
370+
if (FieldName.ID.name().equals(key)) {
371371
return new MetadataBackedField(key, entity, mappingContext, entity.getIdProperty());
372372
}
373373

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

389389
Iterable<?> conditions = keyword.getValue();
390-
List<Object> newConditions = conditions instanceof Collection<?> collection
391-
? new ArrayList<>(collection.size())
390+
List<Object> newConditions = conditions instanceof Collection<?> collection ? new ArrayList<>(collection.size())
392391
: new ArrayList<>();
393392

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

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

627-
if (it.getValue() instanceof Document document) {
626+
if (it.getValue()instanceof Document document) {
628627
map.put(key, getMappedObject(document, entity));
629628
} else {
630629
map.put(key, delegateConvertToMongoType(it.getValue(), entity));
@@ -977,8 +976,6 @@ protected static class Field {
977976

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

980-
private static final String ID_KEY = "_id";
981-
982979
protected final String name;
983980

984981
/**
@@ -1008,7 +1005,7 @@ public Field with(String name) {
10081005
* @return
10091006
*/
10101007
public boolean isIdField() {
1011-
return ID_KEY.equals(name);
1008+
return FieldName.ID.name().equals(name);
10121009
}
10131010

10141011
/**
@@ -1053,7 +1050,7 @@ public boolean isAssociation() {
10531050
* @return
10541051
*/
10551052
public String getMappedKey() {
1056-
return isIdField() ? ID_KEY : name;
1053+
return isIdField() ? FieldName.ID.name() : name;
10571054
}
10581055

10591056
/**
@@ -1222,9 +1219,11 @@ public Class<?> getFieldType() {
12221219

12231220
@Override
12241221
public String getMappedKey() {
1225-
if(getProperty() != null && getProperty().getMongoField().getFieldName().isOfType(Type.KEY)) {
1222+
1223+
if (getProperty() != null && getProperty().getMongoField().getName().isKey()) {
12261224
return getProperty().getFieldName();
12271225
}
1226+
12281227
return path == null ? name : path.toDotPath(isAssociation() ? getAssociationConverter() : getPropertyConverter());
12291228
}
12301229

@@ -1355,7 +1354,7 @@ private static String resolvePath(String source) {
13551354

13561355
/* always start from a property, so we can skip the first segment.
13571356
from there remove any position placeholder */
1358-
for(int i=1; i < segments.length; i++) {
1357+
for (int i = 1; i < segments.length; i++) {
13591358
String segment = segments[i];
13601359
if (segment.startsWith("[") && segment.endsWith("]")) {
13611360
continue;

0 commit comments

Comments
 (0)