Search code examples
javajson-apicrnk

Crnk map different resources for one relation


The question is related to Crnk framework. For example, in JsonApiResource I have a field. And depending on some other values I want this field to have different data. Like the first option:

"data": {
    "id": "1",
    "attributes": {
        "firstData": //some data 
    }
}

And the second one:

"data": {
    "id": "1",
    "attributes": {
        "secondData": //some data 
    }
}

I tried to achieve this by creating abstract class, defining such field in resource, creating 2 subclasses as JsonApiResources and in DTOMapper I set the necessary implementation.

public abstract class AbstractData {
    abstract List<Integer> getValues();
}

@JsonApiResource(type = "v1/first")
public class FirstTypeData extends AbstractData {
    @JsonApiId
    protected int id;

    @JsonProperty("firstData")
    private List<Integer> values;

    //implemented getter
}

@JsonApiResource(type = "v1/second")
public class SecondTypeData extends AbstractData {
    @JsonApiId
    protected int id;

    @JsonProperty("secondData")
    private List<Integer> values;

    //implemented getter
}

@JsonApiResource(type = "v1/basic")
public class BasicDataDTO {
    @JsonApiId
    protected int id;

    @JsonProperty("data")
    private AbstractData data; //FirstTypeData or SecondTypeData is set here in mapper
}

This Works fine. But when I want to make it a relation (I put JsonApiRelation on data field), It crushes.

I would like to call /v1/basic/{id}/data and get

{
    "data": {
        "id": "1",
        "type" : "v1/first",
        "attributes": {
            "firstData": //some data 
        }
    }
}

or

{
    "data": {
        "id": "1",
        "type" : "v1/second",
        "attributes": {
            "secondData": //some data 
        }
    }
}

Is this behavior achievable? Or another approach should be used?


Solution

  • currently AbstractData must be a Resource as well (and have a resource repository backing it). Otherwise the @JsonApiRelation annotation will cause a validation error. But a mechanism similar to @MappedSuperclass of JPA could be worthwhile to add to crnk.