我将所有@ManyToOne
的FetchType
从默认FetchType.EAGER
更改为FetchType.LAZY
。
因此,例如,实体如下所示:
@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/