@Projection declares a named Spring Data REST view for selected properties of an entity, allowing an exported resource to expose a tailored representation instead of the default domain model. section 16.6 section 16.7
Named user summary
A projection can target User entities and expose the name through getName(). It can also compute an address representation with @Value("#{target.address.toString()}") and getAddress(). Naming it summary enables /users/1?projection=summary. section 16.6
Listing 16.12 The UserProjection interface
Path: Ch16/spring-data-rest-projections/src/main/java/com/manning /javapersistence/ch16/model/UserProjection.java @Projection(name = "summary", types = User.class) #1 public interface UserProjection { String getName(); #2 @Value("#{target.address.toString()}") #3 String getAddress(); #3 } #1 The projection is named <kbd>summary</kbd>, and it applies to the <kbd>User</kbd> entities. #2 As the field is called <kbd>name</kbd>, we need to write a <kbd>getName</kbd> method to export it, following the getter names convention. #3 Export the <kbd>address</kbd> according to how it is displayed by the <kbd>toString</kbd> method. We use the <kbd>@Value</kbd> annotation, containing a SpEL expression. We also need to follow the getter names convention, so the method is called <kbd>getAddress</kbd>.
The complete UserProjection declaration shows the @Projection name and target, getter-based property export, and SpEL expression used for a computed value. section 16.6
Use excerptProjection = UserProjection.class on @RepositoryRestResource when the projection should become the default representation for an entire collection, such as /users/. section 16.6
Practical considerations:
- Expose only the information required by a particular consumer rather than every entity field. section 16.6
- Use getter names matching entity properties; use @Value and SpEL when the exported value is computed or formatted. section 16.6
- Treat projections and excerpts as complementary: a request parameter selects a named view, while an excerpt configures a collection default. section 16.6
