小编Sam*_*Sam的帖子

杰克逊在序列化上触发JPA Lazy Fetching

我们有一个后端组件,它通过JPA将数据库(PostgreSQL)数据暴露给RESTful API.

问题是,当发送JPA实体作为REST响应时,我可以看到Jackson触发所有Lazy JPA关系.


代码示例(简化):

import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")//for resolving this bidirectional relationship, otherwise StackOverFlow due to infinite recursion
public class Parent extends ResourceSupport implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long id;

    //we actually use Set and override hashcode&equals
    @OneToMany(mappedBy = "parent", cascade = …
Run Code Online (Sandbox Code Playgroud)

java spring json hibernate jpa

14
推荐指数
1
解决办法
2475
查看次数

标签 统计

hibernate ×1

java ×1

jpa ×1

json ×1

spring ×1