JPA 实体在转换为 JSON 时会出现 stackoverflow 错误

我正在使用 JSON 和 JPA,并且有主要方法来对我的对象进行一些测试。


每当我尝试将 Java 实体转换为 JSON 字符串时,都会出现堆栈溢出错误


String jsonString = gson.toJson(cus1)

如果我在这种情况下使用常规 POJO 作为 DTO,则不会出现错误。但是,当我使用实体类时,为什么会出现堆栈溢出错误?


@Entity

@Table(name = "Customers")

@XmlRootElement

@NamedQueries({

    @NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")

    , @NamedQuery(name = "Customer.findById", query = "SELECT c FROM Customer c WHERE c.id = :id")

    , @NamedQuery(name = "Customer.findByName", query = "SELECT c FROM Customer c WHERE c.name = :name")

    , @NamedQuery(name = "Customer.findByAge", query = "SELECT c FROM Customer c WHERE c.age = :age")})


public class Customer implements Serializable {

private static final long serialVersionUID = 1L;

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Integer id;

private String name;

private int age;

@JoinColumn(name = "city", referencedColumnName = "id")

@ManyToOne(optional = false)

private City city;

//getters, setters and constructor


慕慕森
浏览 440回答 1
1回答

噜噜哒

该错误与 City 序列化 Customer 和 Customer 再次序列化城市有关,导致StackOverflowError.如果您没有在Customer实体中使用城市对象,只需在 json 序列化期间忽略该字段。@XmlRootElementpublic class Customer {&nbsp; &nbsp; @XmlTransient&nbsp; &nbsp; private Set<City> cities;}反之亦然,@XmlTransient在private City city;现场使用。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java