延迟提取问题

时间:2019-10-25 05:23:49

标签: java mysql jpa

我正在尝试获取一个与其他实体类B也有关系的实体A。但是由于A的获取是延迟的,所以我得到了LazyException和JsonMappingException。

我尝试了以下链接: Hibernate + lazy fetch + gson = LazyInitializationException

Hibernate LAZY fetch

@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[&quot;patient&quot;]-&gt;com.cogent.persistence.model.Patient[&quot;surname&quot;]-&gt;com.cogent.persistence.model.Surname$HibernateProxy$D7grS1t7[&quot;ethnicity&quot;]-&gt;com.cogent.persistence.model.Ethnicity$HibernateProxy$f67J9iWj[&quot;name&quot;])
    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)

如何解决此问题?

0 个答案:

没有答案