1

I develop a REST voting system where users can vote on restaurants. I have a Vote class which contains User, Restaurant and Date.

public class Vote extends AbstractBaseEntity {

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    @NotNull
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "restaurant_id")
    private Restaurant restaurant;

    @Column(name = "date", nullable = false)
    @NotNull
    private LocalDate date;

}

I need to find all votes of the day. And if there are several votes for one restaurant, only first object serializes well. The other ones shows restaurant ID instead of Restaurant object as shown below:

[
    {
        "id": 100019,
        "user": null,
        "restaurant": {
            "id": 100004,
            "name": "KFC"
        },
        "date": "2020-08-28"
    },
    {
        "id": 100020,
        "user": null,
        "restaurant": 100004,
        "date": "2020-08-28"
    },
    {
        "id": 100021,
        "user": null,
        "restaurant": {
            "id": 100005,
            "name": "Burger King"
        },
        "date": "2020-08-28"
    },
    {
        "id": 100022,
        "user": null,
        "restaurant": 100005,
        "date": "2020-08-28"
    }
]

So first Vote for KFC shows full restaurant info, but second shows only ID. Same for Burger King which is next 2 votes.

What could be a problem?

  • Can you show us how are you retrieving the votes for a day? The problem might be that you are getting the results as a list of Vote.class, where a vote refers only to one restaurant not a list. – Vladimir Stanciu Aug 28 '20 at 13:41
  • I suspect that "restaurant": 100004 is the foreign key in the table Vote. "restaurant": {...} is the referenced Restaurant object from the other table. Maybe the getter gets called from the JSON serializer and sometimes returns the key rather than the object. To test this theory, you could copy the data into an intermediate (non JPA) pojo and return that object to the REST layer. – aeberhart Aug 28 '20 at 17:28

1 Answers1

1

You need to use com.fasterxml.jackson.annotation.JsonIdentityInfo annotation and declare it for Restaurant class:

@JsonIdentityInfo(generator = ObjectIdGenerators.None.class)
class Restaurant {

    private int id;
    ...
}

See also:

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146