java - Jackson 应用于 JPA 实体以生成 JSON 时出现 Stakover 流错误

标签 java json jpa-2.0 one-to-many yasson

我有一个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 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.

另请参阅:

关于java - Jackson 应用于 JPA 实体以生成 JSON 时出现 Stakover 流错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57333892/

相关文章:

java - JSoup 数据问题

java - 大括号使得 for 循环只运行一次?

java - 包含从 block 读取的映射器的 Hadoop java 文件

json - CloudFormation 存储桶策略 - 缺少必填字段 "Effect"

java - 将嵌套的 JSON 字符串转换为 java 对象列表

java - 使用 CriteriaBuilder 的 JPA 左外连接导致错误 : Partial object queries are not allowed to maintain the cache or be edited

java - 如何使用JPA2.0将属性映射为DB中的Class和Id

java - JPA 和 derby 空指针异常

java - Maven-dependency-plugin 和带有 SOURCE RetentionPolicy 的注释

javascript - 动态添加到 Highcharts