Не удалось записать сообщение HTTP: org.springframework.http.converter.HttpMessageNotWritableException: не удалось записать JSON: ошибка - PullRequest
0 голосов
/ 29 июня 2018

Я использую многомодульное приложение Angular 5 и Java Spring Boot. Класс Employee и адрес имеют отношение один ко многим. Я добавил аннотации @JsonManagedReference, @JsonBackReference, но я получить ошибку при запуске кода Angular:

 Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: com.example.demo.model.Employee_$$_jvstdec_1["handler"])

Классы сущностей указаны ниже:

package com.example.demo.model;

import java.io.Serializable;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonBackReference;

@Entity
@JsonIgnoreProperties(ignoreUnknown=true)
public class Address implements Serializable{

  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private int addId;    
  private int no; 
  private String addLine1;
  private String addLine2;
  private String addLine3;

  @ManyToOne
  @JoinColumn(name = "empId")
  @JsonBackReference
  private Employee employee;

  public int getAddId() {
    return addId;
  }
  public void setAddId(int addId) {
    this.addId = addId;
  }
  public int getNo() {
    return no;
  }
  public void setNo(int no) {
    this.no = no;
  }
  public String getAddLine1() {
    return addLine1;
  }
  public void setAddLine1(String addLine1) {
    this.addLine1 = addLine1;
  }
  public String getAddLine2() {
    return addLine2;
  }
  public void setAddLine2(String addLine2) {
    this.addLine2 = addLine2;
  }
  public String getAddLine3() {
    return addLine3;
  }
  public void setAddLine3(String addLine3) {
    this.addLine3 = addLine3;
  }
  public Employee getEmployee() {
    return employee;
  }
  public void setEmployee(Employee employee) {
    this.employee = employee;
  }
}


package com.example.demo.model;

  import java.io.Serializable;
  import java.util.List;


  import javax.persistence.CascadeType;
  import javax.persistence.Entity;
  import javax.persistence.GeneratedValue;
  import javax.persistence.GenerationType;
  import javax.persistence.Id;
  import javax.persistence.OneToMany;
  import com.fasterxml.jackson.annotation.JsonManagedReference;
  import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

    @Entity
    @JsonIgnoreProperties(ignoreUnknown=true)
    public class Employee implements Serializable {

      @Id
      @GeneratedValue(strategy=GenerationType.IDENTITY)
      private Long empId;
      private String empNo;
      private String empName;
      private String position;  
      @OneToMany(mappedBy="employee", cascade=CascadeType.ALL)
      @JsonManagedReference
      private List<Address> addresses;

      public Long getEmpId() {
        return empId;
      }

      public void setEmpId(Long empId) {
        this.empId = empId;
      }

      public String getEmpNo() {
        return empNo;
      }

      public void setEmpNo(String empNo) {
        this.empNo = empNo;
      }

      public String getEmpName() {
        return empName;
      }

      public void setEmpName(String empName) {
        this.empName = empName;
      }

      public String getPosition() {
        return position;
      }

      public void setPosition(String position) {
        this.position = position;
      }

      public List<Address> getAddresses() {
        return addresses;
      }

      public void setAddresses(List<Address> addresses) {
        this.addresses = addresses;
      }

    }

Ответы [ 2 ]

0 голосов
/ 29 июня 2018

Вам необходимо предоставить конструктор по умолчанию, а также конструктор требуемых параметров, чтобы JPA (или сам Hibernate) мог правильно инициализировать сущность в нужном вам состоянии.

0 голосов
/ 29 июня 2018

Это происходит, если есть пустой компонент и JSON пытается сериализоваться. В вашем случае вы пытаетесь сериализовать ленивое загруженное свойство, которое может или не может быть загружено.
В вашем ObjectMapper настройте следующее:

objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

Должно работать нормально.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...