问题
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 intoJSON
text.Excluding properties can be done with a
@JsonbTransient
annotation. Class properties annotated with@JsonbTransient
annotation are ignored byJSON 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