spring-projects / spring-data-commons

Spring Data Commons. Interfaces and code shared between the various datastore specific implementations.

Home Page:https://spring.io/projects/spring-data

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Repository projections not working when projection type is part of entity object hierarchy

shollander opened this issue · comments

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.

ContainsName is not a projection but a supertype. We do not distinguish between interface supertypes or superclasses. Instead, if a repository query method defines a supertype return type, we materialize the actual object. Only classes and interfaces outside the object hierarchy are considered projections.

Our documentation doesn't call this aspect out explicitly, so it would be good to improve our documentation.