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

后端 未结 2 1375
广开言路
广开言路 2020-12-03 05:36

I made a projection which should expose nested entities:

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


        
相关标签:
2条回答
  • 2020-12-03 05:39

    I'm not going to argue with @Oliver Drotbohm, as this is indeed the correct answer, however, if you want a cheeky workaround, just define a getter for the entity field with a slightly different name (using the OP's example):

    BusinessModel getBusinessInline() { return this.businessModel; }
    

    Will result in a JSON payload of:

    {
        .
        .
        "businessInline": {"name":"stuff etc"}
        .
        .
    }
    

    Presuming your consuming service will accept that, then its an option.

    Not big or clever, but it works.

    0 讨论(0)
  • 2020-12-03 05:46

    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.

    0 讨论(0)
提交回复
热议问题