无限递归与杰克逊JSON和休眠JPA问题

2022-08-31 04:22:47

当尝试将具有双向关联的JPA对象转换为JSON时,我不断得到

org.codehaus.jackson.map.JsonMappingException: Infinite recursion (StackOverflowError)

我所发现的只是这个线程,它基本上以建议避免双向关联结束。有没有人有这个春季错误解决方法的想法?

------ 编辑 2010-07-24 16:26:22 -------

Codesnippets:

业务目标 1:

@Entity
@Table(name = "ta_trainee", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Trainee extends BusinessObject {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    @Column(name = "id", nullable = false)
    private Integer id;

    @Column(name = "name", nullable = true)
    private String name;

    @Column(name = "surname", nullable = true)
    private String surname;

    @OneToMany(mappedBy = "trainee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @Column(nullable = true)
    private Set<BodyStat> bodyStats;

    @OneToMany(mappedBy = "trainee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @Column(nullable = true)
    private Set<Training> trainings;

    @OneToMany(mappedBy = "trainee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @Column(nullable = true)
    private Set<ExerciseType> exerciseTypes;

    public Trainee() {
        super();
    }

    //... getters/setters ...
}

业务目标 2:

import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "ta_bodystat", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class BodyStat extends BusinessObject {

    @Id
    @GeneratedValue(strategy = GenerationType.TABLE)
    @Column(name = "id", nullable = false)
    private Integer id;

    @Column(name = "height", nullable = true)
    private Float height;

    @Column(name = "measuretime", nullable = false)
    @Temporal(TemporalType.TIMESTAMP)
    private Date measureTime;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="trainee_fk")
    private Trainee trainee;
}

控制器:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Controller
@RequestMapping(value = "/trainees")
public class TraineesController {

    final Logger logger = LoggerFactory.getLogger(TraineesController.class);

    private Map<Long, Trainee> trainees = new ConcurrentHashMap<Long, Trainee>();

    @Autowired
    private ITraineeDAO traineeDAO;
     
    /**
     * Return json repres. of all trainees
     */
    @RequestMapping(value = "/getAllTrainees", method = RequestMethod.GET)
    @ResponseBody        
    public Collection getAllTrainees() {
        Collection allTrainees = this.traineeDAO.getAll();

        this.logger.debug("A total of " + allTrainees.size() + "  trainees was read from db");

        return allTrainees;
    }    
}

JPA-学员DAO的实施:

@Repository
@Transactional
public class TraineeDAO implements ITraineeDAO {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public Trainee save(Trainee trainee) {
        em.persist(trainee);
        return trainee;
    }

    @Transactional(readOnly = true)
    public Collection getAll() {
        return (Collection) em.createQuery("SELECT t FROM Trainee t").getResultList();
    }
}

持久性.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
             version="1.0">
    <persistence-unit name="RDBMS" transaction-type="RESOURCE_LOCAL">
        <exclude-unlisted-classes>false</exclude-unlisted-classes>
        <properties>
            <property name="hibernate.hbm2ddl.auto" value="validate"/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
            <!-- <property name="dialect" value="org.hibernate.dialect.HSQLDialect"/>         -->
        </properties>
    </persistence-unit>
</persistence>

答案 1

JsonIgnoreProperties [2017 Update]:

现在,您可以使用 JsonIgnoreProperties 禁止序列化属性(在序列化期间),或忽略读取的 JSON 属性处理(在反序列化期间)。如果这不是您要查找的内容,请继续阅读下面的内容。

(感谢As Zammel AlaaEddine指出这一点)。


JsonManagedReference 和 JsonBackReference

从 Jackson 1.6 开始,您可以使用两个注释来解决无限递归问题,而不会忽略序列化过程中的 getters/setter:@JsonManagedReference@JsonBackReference

解释

为了使 Jackson 运行良好,不应序列化关系的两端之一,以避免导致堆栈溢出错误的不定型循环。

因此,Jackson 采用引用的前向部分(您的实习生类),并以类似 json 的存储格式进行转换;这就是所谓的编组过程。然后,杰克逊寻找参考的背面(即 在 BodyStat 类中),并保持原样,而不是序列化它。关系的这一部分将在前向引用的反序列化(取消编组)期间重新构建。Set<BodyStat> bodyStatsTrainee trainee

你可以像这样改变你的代码(我跳过无用的部分):

业务目标 1:

@Entity
@Table(name = "ta_trainee", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Trainee extends BusinessObject {

    @OneToMany(mappedBy = "trainee", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @Column(nullable = true)
    @JsonManagedReference
    private Set<BodyStat> bodyStats;

业务目标 2:

@Entity
@Table(name = "ta_bodystat", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class BodyStat extends BusinessObject {

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name="trainee_fk")
    @JsonBackReference
    private Trainee trainee;

现在一切都应该正常工作。

如果你想了解更多信息,我在我的博客Keeformatics上写了一篇关于Json和Jackson Stackoverflow问题的文章。

编辑:

你可以检查的另一个有用的注释是@JsonIdentityInfo:使用它,每次Jackson序列化你的对象时,它都会向它添加一个ID(或你选择的另一个属性),这样它就不会每次都完全“扫描”它。当您在更多相互关联的对象之间有一个链循环时,这可能很有用(例如:Order -> OrderLine -> User -> Order,然后一遍又一遍)。

在这种情况下,您必须小心,因为您可能需要多次读取对象的属性(例如,在具有共享同一卖家的更多产品的产品的产品列表中),并且此注释会阻止您这样做。我建议始终查看 firebug 日志,以检查 Json 响应并查看代码中发生的情况。

来源:


答案 2

您可以使用来打破循环(参考)。@JsonIgnore

您需要导入(旧版本)或(当前版本)。org.codehaus.jackson.annotate.JsonIgnorecom.fasterxml.jackson.annotation.JsonIgnore