As mentioned in this answer I've written a DTO like below
class Car {
...
private TransmissionType transmissionType;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "transmissionType")
private Transmission transmission;
}
@JsonSubTypes({
@JsonSubTypes.Type(value = AutomaticTransmission.class, name = "AUTOMATIC"),
@JsonSubTypes.Type(value = ManualTransmission.class, name = "MANUAL")
})
public abstract class Transmission {
}
public class AutomaticTransmission {
public Technology technology; // DCT/CVT/AMT
}
public class ManualTransmission {
public int numGears;
}
Now, while doing POST /api/v1/cars
user can send the transmissionType
but while editing the car i.e. PATCH /api/v1/cars/{id}
, it's bit weird to ask users to send type of car as they've already created the car and service should know it. I was thinking how can I deduce type of car without asking the user.
One solution, I was thinking of writing some interceptor which will get the path parameter id
and from database I'll figure out the type of the car and insert as transmissionType
this way, without user passing transmissionType
controller will get it.
Second solution it to get json body with car but with this approach user won't see strong types and validation needs to be manually done.
What approach should I choose? Is there any other better approach to tackle this problem?
question from:
https://stackoverflow.com/questions/65916952/springboot-figuring-out-type-of-the-field-in-inheritance 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…