toedter / spring-hateoas-jsonapi

A JSON:API media type implementation for Spring HATEOAS
Apache License 2.0
106 stars 15 forks source link

Relationship null #70

Closed jsamaniegog closed 1 year ago

jsamaniegog commented 1 year ago

According to this: https://stackoverflow.com/questions/57411654/correct-null-relationship-in-json-api

This should work: jsonApiModelBuilder.relationship("type", null); But I got this error: "Relationship data object must not be null!"

Am i doing something incorrect? Thank you

toedter commented 1 year ago

Thx for reporting this.

Actually, I was not aware of this use case, imho even if the spec seems to allow it, what would be a practical use case?

jsamaniegog commented 1 year ago

For instance, in a one to many relationship where the foreign key can be null.

Example: "A team can have multiple employees, but an employee may or may not belong to a team." In this case, the employees table will have a "team_id" field that can be null. So i do this: "jsonApiModelBuilder.relationship("team", team);", where team can be null.

JSON:

"relationships": {
    "team": {
      "data": null
    }
}
toedter commented 1 year ago

But wouldn't it be much better, if an employee who has no team, would not have a relationship "team" at all? For instance, often null attributes are simply not transferred in JSON, why not doing the same with non-existing relationships?

But regardless to this discussion: Since the spec supports this use-case, I am considering implementing it...

jsamaniegog commented 1 year ago

I thought the same thing, that's why I searched how it should be and found that on stackoverflow.

toedter commented 1 year ago

I have fixed it in the current snapshot. An empty to-one relationship can be added like

final RepresentationModel<?> jsonApiModel =
        jsonApiModel()
                .model(movie)
                .relationship("director", (Object)null)
                .build();

An empty to-many relationship can be now added like

final RepresentationModel<?> jsonApiModel =
        jsonApiModel()
                .model(movie)
                .relationship("directors", Collections.emptyList())
                .build();

This will be in the next release...

jsamaniegog commented 1 year ago

Thank you for fixing that so quickly!!

toedter commented 1 year ago

Just released version 2.0.2 with this fix.