Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

java - SpringBoot: Figuring out type of the field in inheritance

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, it depends on how you understand the PATCH request. If you always expect the request to contain a whole entity (which would look to me more like a PUT, not a PATCH) than yes, the user needs to include the transmissionType even if it's not changed. I think it's pretty natural. Otherwise, how can you know if the type has not been changed?

On the other hand, with a "real" patch, the user can just sent changed fields and you need to patch an entity retrieved from the DB. In that case, the transmissionType is not needed if it's not altered.

I think it would be more natural to include transmissionType in the Transmission object instead of the Car (changing include to As.PROPERTY). Then, during PATCH, user either does not send transmission at all (no changes) or sends it with the transmissionType.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...