Stakover flow error with Jackson applied on JPA Entities to generate JSON

喜欢而已 提交于 2019-12-02 13:51:38

问题


I have a JPA code with OneToMany relationship. A Customer has a list of Item to check out. However, the code continue to generate StackOverflowError.

Once, I had resolved this one by applying @JsonIgnore while fetching the List<Item> from Customer entity. But even that does not seem to work anymore.

In Customer class:

@OneToMany(mappedBy = "customer", orphanRemoval = true)
@JsonIgnore
private List<Item> items;

In Item class:

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CUSTOMER_ID", nullable = false)
private Customer customer;

And CustomerRest class:

@Path("customers")
public class CustomerRest {

    @Inject
    NewSessionBean newSessionBean;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Customer> getAllCustomers() {
        return newSessionBean.getCustomers();
    }
}

Method newSessionBean.getCustomers():

public List<Customer> getCustomers(){
    TypedQuery<Customer> q= em.createQuery("select c from Customer c", Customer.class);

    return q.getResultList();
}

I expect a nicely formatted JSON message but there is no sign of this. All I get is the java.lang.StackOverflowError on the browser and the Server log generates the following:

Generating incomplete JSON|#]
    java.lang.StackOverflowError
    java.lang.StackOverflowError    at org.eclipse.yasson.internal.serializer.DefaultSerializers.findByCondition(DefaultSerializers.java:130)

回答1:


It looks like you use Yasson project not Jackson. In that case you should use @JsonbTransient annotation. See documentation:

By default, JSONB ignores properties with a non public access. All public properties - either public fields or non public fields with public getters are serialized into JSON text.

Excluding properties can be done with a @JsonbTransient annotation. Class properties annotated with @JsonbTransient annotation are ignored by JSON Binding engine. The behavior is different depending on where @JsonbTransient annotation is placed.

See also:

  • Circular reference issue with JSON-B


来源:https://stackoverflow.com/questions/57333892/stakover-flow-error-with-jackson-applied-on-jpa-entities-to-generate-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!