JAX WS RS JPA does not return Onetomany relation in JSON

Asked

Viewed 63 times

-1

In my relationship, a Call is related to many Histories. The key to the Call is present in each History. When consulting a History by code, there is a @Manytoone relation that returns the Call to which the history belongs. When consulting the Call, the answer should contain the consulted Call and all Histories related to this Call. This relation is mapped in the Called model as @Onetomany.

It is possible to instantiate the History Collection class and generate an output in the console, but the history is not sent in JSON to the client.

Note: All JPA classes were automatically generated from Netbeans using "New > Database Entity Class...".

1 answer

0


After many researches, I arrived at the following solution.

The Called model must contain in the Historical Collection attribute the annotation that informs the relation type and as a parameter the load type must be passed: LAZY or EAGER. In my case EAGER was necessary to always bring the history.

@OneToMany(cascade = CascadeType.ALL, mappedBy = "chamado", fetch = FetchType.EAGER)
@JsonManagedReference
private Collection<Historico> historicoCollection;

In the Historical class the mapping is this way.

@JoinColumn(name = "chamado", referencedColumnName = "codigo")
@ManyToOne(optional = false)
@JsonBackReference
private Chamado chamado;

I also had to delete the @Xmltransiente annotation.

//@XmlTransient
public Collection<Historico> getHistoricoCollection() {
    return historicoCollection;
}

As shown in the following question:

https://stackoverflow.com/questions/21752912/jax-rs-expose-onetomany-entities-in-get

After deleting the @Xmltransiente annotation in the annotation, a recursive error is generated. For so much is explained at this link the solution to the problem, which is only to inform who is the class that contains the relation, through the @Jsonbackreference and @Jsonmanagedreference annotations.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.