[org.springframework.http.converter.HttpMessageNotWritableException: не удалось записать JSON: бесконечная рекурсия (StaJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 [org.springframework.http.converter.HttpMessageNotWritableException: не удалось записать JSON: бесконечная рекурсия (Sta

Сообщение Anonymous »

У меня есть два класса сущностей: Country и State, которые имеют следующую связь. Несмотря на то, что я пометил страну как ленивую в объекте State, она все еще пытается получить ее, и я получаю бесконечный ответ JSON о стране и штате, что вызывает бесконечную рекурсию (StackOverflowError). Я знаю, что могу решить эту проблему, используя @JsonIgnore поверх State в классе Country. Но почему состояние извлекается даже после того, как оно помечено как (fetch = FetchType.LAZY)?
package com.bezkoder.springjwt.models;

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

@Entity
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@OneToMany(mappedBy = "country", cascade = CascadeType.ALL)
//@JsonIgnore
private List states;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List getStates() {
return states;
}

public void setStates(List states) {
this.states = states;
}

@Override
public String toString() {
return "Country{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

State.java
package com.bezkoder.springjwt.models;

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

@Entity
public class State {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "country_id")
private Country country;

@OneToMany(mappedBy = "state", cascade = CascadeType.ALL)
private List cities;

public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Country getCountry() {
return country;
}

public void setCountry(Country country) {
this.country = country;
}

public List getCities() {
return cities;
}

public void setCities(List cities) {
this.cities = cities;
}
@Override
public boolean equals(Object obj) {

if (this == obj) {
return true;
}

if (obj == null) {
return false;
}

if (getClass() != obj.getClass()) {
return false;
}

return id != null && id.equals(((State) obj).id);
}

@Override
public int hashCode() {
return 2021;
}
@Override
public String toString() {
return "State{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

Исключение
Hibernate: select country0_.id as id1_1_, country0_.name as name2_1_ from country country0_
Hibernate: select states0_.country_id as country_3_10_0_, states0_.id as id1_10_0_, states0_.id as id1_10_1_, states0_.country_id as country_3_10_1_, states0_.name as name2_10_1_ from state states0_ where states0_.country_id=?
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at open/src/java.instrument/share/native/libinstrument/JPLISAgent.c line: 873
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at open/src/java.instrument/share/native/libinstrument/JPLISAgent.c line: 873
2024-03-16 17:54:22.052 WARN 31312 --- [nio-8771-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Infinite recursion (StackOverflowError) (through reference chain: com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]->com.bezkoder.springjwt.models.State["country"]->com.bezkoder.springjwt.models.Country["states"]->org.hibernate.collection.internal.PersistentBag[0]-


Подробнее здесь: https://stackoverflow.com/questions/781 ... ould-not-w
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»