FetchType.LAZY在休眠中不适用于@ManyToOne映射

时间:2019-02-22 13:47:28

标签: java hibernate persistence lazy-loading many-to-one

简单地说,我在Child类和Parent类之间存在多对一的关系。我想加载所有孩子,而不必加载他们的父母详细信息。 我的孩子班是

@Entity

public class Child implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private String name;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parentId", referencedColumnName = "id")
private Parent parent;

public Child() {
}
// Getters and setters here
}

我的父母班是

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

private String name;

public Parent() {
}
}

我有一个休息控制器,我想用它来获取所有没有父母的孩子

@GetMapping
public List<Child> getChildren() {
    return childRepository.findAll();
}

当我运行它时,它会抛出

 {
  "timestamp": "2019-02-22T13:45:31.219+0000",
  "status": 500,
  "error": "Internal Server Error",
  "message": "Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.example.attendance.models.Child[\"parent\"]->com.example.attendance.models.Parent$HibernateProxy$1QzJfFPz[\"hibernateLazyInitializer\"])",
  "trace": "org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.example.attendance.models.Child[\"parent\"]->com.example.attendance.models.Parent$HibernateProxy$1QzJfFPz[\"hibernateLazyInitializer\"])\n\tat org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter.writeInternal(AbstractJackson2HttpMessageConverter.java:293)\n\tat org.springframework.http.converter.AbstractGenericHttpMessageConverter.write(AbstractGenericHttpMessageConverter.java:103)\n\tat org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:290)\n\tat org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:180)

我应该进行哪些更改以便可以延迟加载父类?

谢谢。

1 个答案:

答案 0 :(得分:1)

您已经懒加载了父类。发生异常是因为在加载父对象之前序列化了Child对象。要禁用它,您可以使用以下注释您的Child类: @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})

在那之后,Parent在序列化中将被忽略。