我有一个JPA
代码为 OneToMany
关系。一个Customer
有一个列表 Item
去检查一下。但是,代码继续生成StackOverflowError
。
有一次,我通过应用@JsonIgnore
解决了这个问题。在获取List<Item>
时来自客户实体。但即使这样似乎也不再起作用了。
在 Customer
类:
@OneToMany(mappedBy = "customer", orphanRemoval = true)
@JsonIgnore
private List<Item> items;
在 Item
类:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CUSTOMER_ID", nullable = false)
private Customer customer;
和CustomerRest
类:
@Path("customers")
public class CustomerRest {
@Inject
NewSessionBean newSessionBean;
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<Customer> getAllCustomers() {
return newSessionBean.getCustomers();
}
}
方法newSessionBean.getCustomers()
:
public List<Customer> getCustomers(){
TypedQuery<Customer> q= em.createQuery("select c from Customer c", Customer.class);
return q.getResultList();
}
我期望收到格式良好的 JSON 消息,但没有任何迹象。我得到的只是 java.lang.StackOverflowError
在浏览器和服务器日志上生成以下内容:
Generating incomplete JSON|#]
java.lang.StackOverflowError
java.lang.StackOverflowError at org.eclipse.yasson.internal.serializer.DefaultSerializers.findByCondition(DefaultSerializers.java:130)
最佳答案
看起来您使用 Yasson项目不Jackson 。在这种情况下,您应该使用 @JsonbTransient 注释。请参阅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.
另请参阅:
关于java - Jackson 应用于 JPA 实体以生成 JSON 时出现 Stakover 流错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333892/