Skip to content

Unwrap LazyLoadingProxy before checking isNew. #5033

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>5.0.0-SNAPSHOT</version>
<version>5.0.x-GH-5031-SNAPSHOT</version>
<packaging>pom</packaging>

<name>Spring Data MongoDB</name>
Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb-distribution/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>5.0.0-SNAPSHOT</version>
<version>5.0.x-GH-5031-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
2 changes: 1 addition & 1 deletion spring-data-mongodb/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
<parent>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-parent</artifactId>
<version>5.0.0-SNAPSHOT</version>
<version>5.0.x-GH-5031-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import org.bson.types.ObjectId;
import org.jspecify.annotations.Nullable;
import org.springframework.data.mapping.PersistentPropertyAccessor;
import org.springframework.data.mongodb.core.convert.LazyLoadingProxy;
import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity;
import org.springframework.data.mongodb.core.query.Collation;
import org.springframework.data.mongodb.repository.query.MongoEntityInformation;
Expand Down Expand Up @@ -107,6 +108,13 @@ public Class<ID> getIdType() {
return fallbackIdType;
}

@Override
public boolean isNew(T entity) {

T unwrapped = entity instanceof LazyLoadingProxy proxy ? (T) proxy.getTarget() : entity;
return super.isNew(unwrapped);
}

@Override
public boolean isVersioned() {
return this.entityMetadata.hasVersionProperty();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ public enum Sex {
User unwrappedUser;

@DocumentReference User spiritAnimal;
@DocumentReference(lazy = true) User lazySpiritAnimal;

int visits;

Expand Down Expand Up @@ -325,6 +326,14 @@ public void setSpiritAnimal(User spiritAnimal) {
this.spiritAnimal = spiritAnimal;
}

public User getLazySpiritAnimal() {
return lazySpiritAnimal;
}

public void setLazySpiritAnimal(User lazySpiritAnimal) {
this.lazySpiritAnimal = lazySpiritAnimal;
}

@Override
public int hashCode() {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@
*/
package org.springframework.data.mongodb.repository;

import static org.assertj.core.api.Assertions.*;
import static org.springframework.data.mongodb.core.convert.LazyLoadingTestUtils.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNoException;
import static org.springframework.data.mongodb.core.convert.LazyLoadingTestUtils.assertProxyIsResolved;

import java.util.ArrayList;
import java.util.Arrays;
Expand All @@ -37,12 +38,14 @@
*
* @author Thomas Darimont
* @author Oliver Gierke
* @author Christoph Strobl
*/
@ContextConfiguration(locations = "PersonRepositoryIntegrationTests-context.xml")
@ExtendWith(SpringExtension.class)
public class PersonRepositoryLazyLoadingIntegrationTests {

@Autowired PersonRepository repository;
@Autowired UserRepository userRepository;
@Autowired MongoOperations operations;

@BeforeEach
Expand Down Expand Up @@ -123,4 +126,47 @@ public void shouldLoadAssociationWithDbRefOnConcreteDomainClassAndLazyLoadingEna
assertProxyIsResolved(coworker, true);
assertThat(coworker.getUsername()).isEqualTo(thomas.getUsername());
}

@Test // GH-5031
void allowsSavingEntityLoadedViaLazyDBRef() {

User thomas = new User();
thomas.id = "tom";
thomas.username = "Thomas";
userRepository.save(thomas);

Person oliver = new Person();
oliver.id = "ollie";
oliver.setFirstname("Oliver");
oliver.coworker = thomas;
repository.save(oliver);

Person loaded = repository.findById(oliver.id).get();
User coworker = loaded.getCoworker();
assertThat(coworker.getUsername()).isEqualTo(thomas.getUsername());

assertThatNoException().isThrownBy(() -> userRepository.save(coworker));
}

@Test // GH-5031
void allowsSavingEntityLoadedViaLazyDocumentReference() {

User thomas = new User();
thomas.id = "tom";
thomas.username = "Thomas";
userRepository.save(thomas);

Person oliver = new Person();
oliver.id = "ollie";
oliver.setFirstname("Oliver");
oliver.lazySpiritAnimal = thomas;
repository.save(oliver);

Person loaded = repository.findById(oliver.id).get();
User spiritAnimal = loaded.getLazySpiritAnimal();
assertThat(spiritAnimal.getUsername()).isEqualTo(thomas.getUsername());

assertThatNoException().isThrownBy(() -> userRepository.save(spiritAnimal));
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* Copyright 2025 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.repository;

import org.springframework.data.repository.CrudRepository;

/**
* @author Christoph Strobl
*/
public interface UserRepository extends CrudRepository<User, String> {}
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,9 @@
</property>
</bean>

<bean class="org.springframework.data.mongodb.repository.support.MongoRepositoryFactoryBean">
<constructor-arg value="org.springframework.data.mongodb.repository.UserRepository"/>
<property name="mongoOperations" ref="mongoTemplate"/>
</bean>

</beans>
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,12 @@ Required properties that are also defined as lazy loading ``DBRef`` and used as

TIP: Lazily loaded ``DBRef``s can be hard to debug.
Make sure tooling does not accidentally trigger proxy resolution by e.g. calling `toString()` or some inline debug rendering invoking property getters.
Please consider to enable _trace_ logging for `org.springframework.data.mongodb.core.convert.DefaultDbRefResolver` to gain insight on `DBRef` resolution.
Please consider to enable _trace_ logging for `org.springframework.data.mongodb.core.convert.DefaultDbRefResolver` to gain insight on `DBRef` resolution. +
Though technically possible, avoid saving back individual lazily loaded entities obtained via properties of the referencing root.

CAUTION: Lazy loading may require class proxies, that in turn, might need access to jdk internals, that are not open, starting with Java 16+, due to https://openjdk.java.net/jeps/396[JEP 396: Strongly Encapsulate JDK Internals by Default].
For those cases please consider falling back to an interface type (eg. switch from `ArrayList` to `List`) or provide the required `--add-opens` argument.
For those cases please consider falling back to an interface type (eg. switch from `ArrayList` to `List`) or provide the required `--add-opens` argument. +


[[mapping-usage.document-references]]
== Using Document References
Expand Down Expand Up @@ -500,6 +502,7 @@ A few more general remarks:
* Do you use cyclic references?
Ask your self if you need them.
* Lazy document references are hard to debug.
Make sure tooling does not accidentally trigger proxy resolution by e.g. calling `toString()`.
Make sure tooling does not accidentally trigger proxy resolution by e.g. calling `toString()`. +
Though technically possible, avoid saving back individual lazily loaded entities obtained via properties of the referencing root.
* There is no support for reading document references using reactive infrastructure.
====