I created two JPA entity classes to represent the following tables:
I think that the one-to-one relationship I setup is incorrrect because I am getting the error:
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: ca.allauto.ups.model.Vehicle["model"]->ca.allauto.ups.model.VehicleModel$HibernateProxy$zuv5wN1w["hibernateLazyInitializer"])
Here is the vehicle class:
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;
}
And this is the 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;
}
I would like for the vehicle class to be returned so that it includes the vehicle model as a nested object, as in:
{
id: 1,
year: 2022,
model: {
id: 2,
model: "Toyota Prius"
},
doors: 4,
vehicle_type: "Hatchback",
color: "Blue",
etc...
}
Any ideas what I'm doing wrong?
The default Jackson serializer does not like it when you use nested objects. The following code worked for me when it came to serializing nested objects:
@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;
}