-
Notifications
You must be signed in to change notification settings - Fork 0
How to use projections in Java
Projections are a way for a client to request only specific fields from an object instead of the entire object. Using projections when you only need a few fields from an object is a good way to self-document your code and reduce payload of responses. You can read more about projections here: Projections
Using projections in java code relies heavily on PathSpec
objects, which represent specific fields of an object. To get a PathSpec
of a field bar of a RecordTemplate object Foo, you would write the following:
PathSpec pathSpec = Foo.fields().bar();
It is not possible to set projections for non-RecordTemplate objects.
Projections are set by the request builder. To set a request projection, create your builder as you normally would, and then add your projection to it:
builder.fields(pathSpec);
the fields()
method can take as arguments any number of PathSpecs, or an array of them.
builder.fields(pathSpec1, pathSpec2, pathSpec3);
builder.fields(pathSpecArray);
This will create a positive projection for your given fields. The request will only return fields that you have specified with .fields(...)
.
No. If you want a large number of fields you will need to include them all in the .fields(...)
method call.
At present, you cannot make nested projections using the Java client.
In general, examining a request’s projections on the server side will not be necessary. When the server returns an object to the client, the rest framework will take care of stripping all unrequested fields. It is not necessary for the server to examine the projection and strip fields itself.
However, it is possible for the server to examine a request’s projection.
MaskTree projections = getContext().getProjectionMask();
this will get you the projections of a request. If there were no projections, this will be null.
If there were projections, you can check the status of each field.
MaskOperation mask = projections.getOperations.get(pathSpec);
if (mask == MaskOperation.POSITIVE_MASK_OP)
{
// field is requested.
}
if (mask == MaskOperation.NEGATIVE_MASK_OP)
{
// field is not requested.
}
You can then use this information in whatever way you wish to.
- Dynamic Discovery (D2)
- Data Schema and Templates
-
Rest.li
- Server
- Client
- Projections
- Tools
- FAQs