我正在使用 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
1 回答
噜噜哒
TA贡献1784条经验 获得超7个赞
该错误与 City 序列化 Customer 和 Customer 再次序列化城市有关,导致StackOverflowError.
如果您没有在Customer实体中使用城市对象,只需在 json 序列化期间忽略该字段。
@XmlRootElement
public class Customer {
@XmlTransient
private Set<City> cities;
}
反之亦然,@XmlTransient在private City city;现场使用。
添加回答
举报
0/150
提交
取消