javaspringspring-data-rest

Use distinct projections according to child classes when inlining an abstract type


I have the following entities (irrelevant parts omitted):

@Entity    
public class Chart {
    
    @ManyToOne
    private Parameter parameter;

}

@Entity
@DiscriminatorColumn(name="category")
public abstract class Parameter {

    private String label;    

    @OneToMany(mappedBy="parameter")
    private Set<TimeSerie> timeSeries = new HashSet<TimeSerie>();

    ...
}

@Entity
@DiscriminatorValue(value="analog")
public class AnalogParameter extends Parameter {

    private String resolution;
    
}

@Entity
@DiscriminatorValue(value="digital")
public class DigitalParameter extends Parameter {
    ...
}

And the following projection and nested-projection:

@Projection(name = "parameterInlinedChart, types = { Chart.class })
public interface ParameterInlinedChart {
    TimeSeriesInlinedParameter getParameter();
}

@Projection(name = "timeSeriesInlinedParameter , types = { Parameter.class })
public interface TimeSeriesInlinedParameter {
    ...
}

I would like to make the properties specific to children classes of the abstract Parameter class to appear on the JSON output when using the 'parameterInlinedChart' projection.

Using the example above, I would like to have the "resolution" property of the AnalogParameter, if the Parameter is of type AnalogParameter.

Simply adding this property on the "timeSeriesInlinedParameter" projection throws an exception if the Parameter is of type DigitalParameter

I tried to create projections exclusives to AnalogParameter and DigitalParameter, but I don't know how to tell the "parameterInlinedChart" projection to conditionally use the right depending on the type of the child Parameter class to serialize.

Is it even possible ?

The problem might not be easy to understand, I can give more details if needed.


Solution

  • This is currently not possible. I've created an Improvement request for this and even implemented this in a Pull Request. Admittedly this required a lot of changes to existing structure of Jackson2 serialization module, as well as introduction of a new field to support the projection hierarchy, so it's not clear when this will be merged.

    Perhaps you can vote for the JIRA issue if this is important for you.