Description
The use of class or interface projection by declaring the return type of the repository method to be a class or interface with a limited number of fields does not work properly when the projection class or interface is part of the object hierarchy of the Entity object.
For example, given:
@Document("collection=my_entities")
public class MyEntity implements ContainsName {
private String id;
private String name;
private String other;
// getters/setters
}
public interface ContainsName {
String getName();
}
public interface MyEntityRepository extends MongoRepository<MyEntity, String> {
ContainsName findNameOnlyByName(String name);
}
The return value of MyEntityRepository.findNameOnlyByName("someName")
will be a MyEntity
object that contains all the fields of entity, not just fields defined in the given interface. The behavior is the same whether ContainsName
is an interface or an abstract class. Only when the return type of the method is outside of the entity object hierarchy will a true projection query created. While this issue does not cause errors, it is a performance issue since the benefits of using a projection and returning a limited set of data are not realized.