javaspringhibernateentitymanagerhibernate-entitymanager

Hibernate maps full relational object only in first occurance in the aggregation


Problem I have stumbbled upon is the relation below in my RestApi. While requesting for all payments Object having PaymentCategory in relation is fully returned. But when PaymentCategory in the List is present for the next time, then the Payment object contains only an Id of PaymentCategory.

snippet Payment.class

    @ManyToOne(cascade = CascadeType.DETACH, fetch = FetchType.EAGER)
    private PaymentCategory paymentCategory;

PaymentCategory.class

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
public class PaymentCategory {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
}

Response querying all Payments

[
    {
        "id": 1,
        "name": "Hipoteka",
        "description": "Hipoteka w banku PEKAO SA",
        "paymentDate": "2022-10-11",
        "lastPaymentDate": "2022-09-11",
        "paymentDueDay": 11,
        "amount": 13.13,
        "paymentClosed": false,
        "paymentClosingDate": null,
        "paymentCategory": {
            "id": 1,
            "name": "Dom"
        },
        "logo": "WAPBouvlSP6gEKLEPjl/7Hmul8o=",
        "repayments": []
    },
    {
        "id": 2,
        "name": "Spotify",
        "description": "Spotify premium",
        "paymentDate": "2022-10-25",
        "lastPaymentDate": "2022-09-25",
        "paymentDueDay": 25,
        "amount": 29.99,
        "paymentClosed": false,
        "paymentClosingDate": null,
**        "paymentCategory": {
            "id": 2,
            "name": "Rozrywka"
        },**
        "logo": "WAPBouvlSP6gEKLEPjl/7Hmul8o=",
        "repayments": []
    },
    {
        "id": 3,
        "name": "Viaplay",
        "description": "Viaplay abonament",
        "paymentDate": "2022-10-11",
        "lastPaymentDate": "2022-09-17",
        "paymentDueDay": 17,
        "amount": 34.0,
        "paymentClosed": false,
        "paymentClosingDate": null,
        **"paymentCategory": 2,**
        "logo": "WAPBouvlSP6gEKLEPjl/7Hmul8o=",
        "repayments": []
    }
]

What am I missing here? Is there an additional configuration for entityManager?

Best Regards, Mateusz

I have tried looking in some guides, but I didn't find solution I've expected.


Solution

  • @JsonIdentityInfo in PaymentCategory was actually limiting the object property.

    There is no use in this class due to due to single directional relation.