java 为什么我得到一个JacksonNo serializer found error for JPA entity on OneToOne mapping?

gab6jxml  于 2023-06-04  发布在  Java
关注(0)|答案(1)|浏览(96)

我创建了两个JPA实体类来表示以下表:

我认为我设置的一对一关系是不正确的,因为我得到了错误:
com.fasterxml.Jackson.databind.exc.InvalidDefinitionException:未找到org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor类的序列化器,也未发现创建BeanSerializer的属性(为避免异常,请禁用SerializationFeature.FAIL_ON_EMPTY_BEANS)(通过引用链:ca.allauto.ups.model.Vehicle[“model”]->ca.allauto.ups.model.VehicleModel$HibernateProxy$zuv5wN1w[“hibernateLazyInitializer”])
以下是车辆类:

package ca.allauto.ups.model;

@Entity
@Table(name = "vehicle")
@Data
public class Vehicle {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private Long id;
    
    @Column(name="year")
    private short year;
    
    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "model_id", referencedColumnName = "id")
    private VehicleModel model;
    
    @Column(name="doors")
    private DoorsEnum doors;
    
    @Column(name="vehicle_type")
    private VehicleTypeEnum vehicleType;
    
    @Column(name="color")
    private ColorEnum color;
    
    @Column(name="odometer")
    private Long odometer;
    
    @Column(name="kms_miles")
    private KmsOrMilesEnum kmsOrMiles;
    
    @Column(name="transmission")
    private TransmissionEnum transmission;
    
    @Column(name="vin")
    private String vin;
}

这就是VehicleModel:

@Entity
@Table(name = "vehicle_model")
@Data
public class VehicleModel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private Long id;
    
    @Column(name="model")
    private String model;
    
    // I took this out because it was causing the server to crash
    //@OneToOne(mappedBy = "model")
   // private Vehicle vehicle;
    
}

我希望返回vehicle类,以便它将车辆模型作为嵌套对象包含在内,如下所示:

{
  id: 1,
  year: 2022,
  model: {
    id: 2,
    model: "Toyota Prius"
  },
  doors: 4,
  vehicle_type: "Hatchback",
  color: "Blue",
  etc...
}

知道我哪里做错了吗

crcmnpdw

crcmnpdw1#

默认的Jackson序列化程序不喜欢使用嵌套对象。下面的代码在序列化嵌套对象时对我有用:

@GetMapping(path = "/your/path")
public String getNestedObject() {
    Vehicle myV = new Vehicle(/*init*/);
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibiliy(PropertyAccessor.ALL, 
    JsonAutoDetect.Visibility.ANY);
    String json = mapper.writeValueAsString(myV);
    return json;
}

相关问题