我将所有FetchType
的@ManyToOne
从默认的FetchType.LAZY
更改为FetchType.EAGER
。
因此,实体看起来像这样:
@Data
@NoArgsConstructor
@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)
public class DailyEntry {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
// more attributes
@ManyToOne(fetch = FetchType.LAZY)
private Project project;
@ManyToOne(fetch = FetchType.LAZY)
private Employee employee;
}
但是,每次执行获取实体的请求时,我都会收到以下错误:
ERROR 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]->de.hiqs.dailyentry.DailyEntry["project"]->de.hiqs.project.Project$HibernateProxy$cmEQxiMb["customer"]->de.hiqs.customer.Customer$HibernateProxy$BV240DdJ["hibernateLazyInitializer"])
由于错误状态,我可以禁用SerializationFeature.FAIL_ON_EMPTY_BEANS,一切都会正常运行。但是,这是我应该做的还是解决此问题的常用方法?
最佳答案
为了在ToOne关系中启用延迟加载,Hibernate在引用中放置了一个代理而不是真实对象。
为了序列化您的bean,您必须确保引用已初始化。例如,通过调用getter或使用EntityGraph:
https://thoughts-on-java.org/jpa-21-entity-graph-part-1-named-entity/