Why is an excerpt projection not applied automatically for a Spring Data REST item resource?

nKognito picture nKognito · May 13, 2015 · Viewed 10.8k times · Source

I made a projection which should expose nested entities:

@Projection(name = "inlineBusiness", types = { UserModel.class })
public interface InlineBusinessUserModelProjection {

    String getUsername();

    String getFirstName();

    String getLastName();

    Date getBirthdate();

    String getEmail();

    BusinessModel getBusiness();
}

And the service repository:

@RepositoryRestResource(collectionResourceRel = "users", path = "users",
       excerptProjection = InlineBusinessUserModelProjection.class)
public interface UserRepository extends BaseDAO<UserModel> {..}

for /users it works fine, the business field is exposed with nested entity, but when I call /users/1- nothing, also all the custom methods.. Seems like projection isn't involved on any methods except of /users Any ideas?

Answer

Oliver Drotbohm picture Oliver Drotbohm · May 18, 2015

That works as designed. An excerpt projection is used whenever an instance of the target type (UserModel in your case) is used within in an _embedded clause. Thus the excerpt is some kind of preview used everywhere the resource itself is not rendered but pointed to. This is usually the case from collection resources or for associations.

Using an excerpt projection by default on an item resource doesn't really make sense from another point of view: excerpt projections are a read-only view on some domain object. If you return that view for an item resource by default, how would a client know which data it had to send to update the resource. A JSON document created for an excerpt projection, can't be simply taken, modified and used to send a PUT request to update the resource – by definition.

If you want to apply a projection to the item resource, populate the projection URI template variable with the name of the projection.

EDIT: In case the projections don't get applied if you manually select them make sure InlineBusinessUserModelProjection is actually registered for general use. Be sure the type is located in the very same package or sub-package of UserModel. Alternatively manually register the projection via RepositoryRestConfiguration.projectionConfiguration().addProjection(…). Manual configuration makes the use of @Projection on the projection type obsolete.

Read more on this topic in the Spring Data REST reference documentation.