我正在尝试获取一个与其他实体类B也有关系的实体A。但是由于A的获取是延迟的,所以我得到了LazyException和JsonMappingException。
我尝试了以下链接: Hibernate + lazy fetch + gson = LazyInitializationException
@Getter
@Setter
@NoArgsConstructor
@Entity
@Table(name = "patient")
public class Patient implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "first_name", nullable = false, length = 50)
private String firstName;
@Column(name = "middle_name", length = 50)
private String middleName;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "surname_id")
private Surname surname;
}
@Entity
@Table(name = "surname")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Surname implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name")
private String name;
@Column(name = "status")
private Character status;
@Column(name = "remarks")
private String remarks;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "ethnicity_id")
private Ethnicity ethnicity;
}
引发异常:
The server encountered an unexpected condition that prevented it from fulfilling the request.</p><p><b>Exception</b></p><pre>org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: could not initialize proxy [com.cogent.persistence.model.Ethnicity#1] - no Session; nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy [com.cogent.persistence.model.Ethnicity#1] - no Session (through reference chain: com.cogent.patientregistration.dto.response.patient.PatientResponseDTO["patient"]->com.cogent.persistence.model.Patient["surname"]->com.cogent.persistence.model.Surname$HibernateProxy$D7grS1t7["ethnicity"]->com.cogent.persistence.model.Ethnicity$HibernateProxy$f67J9iWj["name"])
org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:296)
org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:103)
org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)
如何解决此问题?