Support @DocumentReference via Querydsl.

Closes #4037
Original pull request: #4069.
This commit is contained in:
Christoph Strobl
2022-05-30 11:34:08 +02:00
committed by Mark Paluch
parent 40320136f3
commit fadca10f62
2 changed files with 35 additions and 3 deletions

View File

@@ -22,7 +22,6 @@ import java.util.Set;
import java.util.regex.Pattern;
import org.bson.Document;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.data.mongodb.core.convert.QueryMapper;
@@ -158,8 +157,20 @@ class SpringDataMongodbSerializer extends MongodbDocumentSerializer {
MongoPersistentProperty property = getPropertyFor(path);
return property.isIdProperty() ? asReference(constant.getConstant(), path.getMetadata().getParent())
: asReference(constant.getConstant(), path);
if (property.isDocumentReference()) {
return converter.toDocumentPointer(constant.getConstant(), property).getPointer();
}
if (property.isIdProperty()) {
MongoPersistentProperty propertyForPotentialDbRef = getPropertyForPotentialDbRef(path);
if (propertyForPotentialDbRef != null && propertyForPotentialDbRef.isDocumentReference()) {
return converter.toDocumentPointer(constant.getConstant(), propertyForPotentialDbRef).getPointer();
}
return asReference(constant.getConstant(), path.getMetadata().getParent());
}
return asReference(constant.getConstant(), path);
}
@Nullable

View File

@@ -50,6 +50,7 @@ import com.querydsl.core.types.dsl.BooleanOperation;
import com.querydsl.core.types.dsl.PathBuilder;
import com.querydsl.core.types.dsl.SimplePath;
import com.querydsl.core.types.dsl.StringPath;
import org.springframework.data.mongodb.repository.User;
/**
* Unit tests for {@link SpringDataMongodbSerializer}.
@@ -225,6 +226,26 @@ public class SpringDataMongodbSerializerUnitTests {
assertThat(serializer.handle(testExpression)).isEqualTo(expected);
}
@Test // GH-4037
void parsesDocumentReference() {
User user = new User();
user.setId("007");
Predicate predicate = QPerson.person.spiritAnimal.eq(user);
assertThat(serializer.handle(predicate)).isEqualTo(Document.parse("{ 'spiritAnimal' : '007' }"));
}
@Test // GH-4037
void parsesDocumentReferenceOnId() {
User user = new User();
user.setId("007");
Predicate predicate = QPerson.person.spiritAnimal.id.eq("007");
assertThat(serializer.handle(predicate)).isEqualTo(Document.parse("{ 'spiritAnimal' : '007' }"));
}
class Address {
String id;
String street;