首页 > 解决方案 > 从数据库表读取到@Entity 模型会产生“未找到序列化程序”错误

问题描述

当我尝试从数据库表读取到 @Entity 回测时,我收到以下错误:

{"timestamp":"2021-01-13T00:42:52.516+00:00","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: net.tekknow.moneymachine.model.JsonResponse[\"data\"]->java.util.ArrayList[0]->net.tekknow.moneymachine.model.Backtest[\"strategy\"]->net.tekknow.moneymachine.model.Strategy$HibernateProxy$NY2C2PBb[\"hibernateLazyInitializer\"])","details":"uri=/api/v1/backtests"}

@Entity 回测包含一个属性“策略策略”。从错误消息中,我猜它不喜欢 Backtest 实体中存在的“策略”字段,但不喜欢相应的 mysql 表中的字段。所有属性都是公共的,并且包含 getter 和 setter。

@Entity
@Table(name="backtest")
public class Backtest {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) 
    private Long id;
    
    @JsonManagedReference       //This prevents an "infinite recursion" error.  Might not need it anymore because I've since added FetchType.LAZY
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="strategy_id", nullable=false) //strategy_id will be the name of the foreign key in the backtest table that points to the primary key of the strategy table
    Strategy strategy;

hibernate save() 命令正确地创建数据并将其存储到表中。所有列都匹配回测属性,当然除了作为对象的“策略”属性。但是hibernate也会创建一个名为“strategy_id”的外键来代替它。我怀疑将数据读回相同的 @Entity Backtest 会导致序列化错误。

@GetMapping("/backtests") 
public JsonResponse getUserBacktests(@RequestParam int userId) {
    List<Backtest> backtests = backtestService.getUserBacktests(userId);
    JsonResponse response = new JsonResponse();
    response.setStatus("success");
    response.setData(backtests);
    return response;
}

这必须是一个普遍的问题。有没有通用的解决方案?

标签: javamysqlhibernate

解决方案


推荐阅读