Can we Convert more than one entity into single Dto in Spring boot

Viewed 31

Can we Convert More Than One Entity into single DTO I have two entity Car And Truck and I want to pass single Entity VehcileDto on Thymleaf page is it possible or not?

1 Answers

That's not necessarily a Spring Boot topic but rather a Java topic.

Say you got the following classes:

/**
 * In this class you would define the Car Entity with all its fields and relations
 */
public class CarEntity {

    private String someCarField;
    private String anotherCarField;

    public String getSomeCarField() {
        return someCarField;
    }

    public void setSomeCarField(String someCarField) {
        this.someCarField = someCarField;
    }

    public String getAnotherCarField() {
        return anotherCarField;
    }

    public void setAnotherCarField(String anotherCarField) {
        this.anotherCarField = anotherCarField;
    }
}

Your Truck Entity would look very similar.

Then you define a DTO:

/**
 * Here you would define the DTO. The DTO is just two Entities in one WrapperObject (See Definition of DTO in Java).
 * This includes all the fields you want to use on your thymeleaf UI.
 * This is the DTO you would put into your model using the MVC Controller
 */
public class VehicleDTO {

    private String someTruckField;
    private String anotherTruckField;

    private String someCarField;
    private String anotherCarField;

    public VehicleDTO(String someTruckField, String anotherTruckField, String someCarField, String anotherCarField) {
        this.someTruckField = someTruckField;
        this.anotherTruckField = anotherTruckField;
        this.someCarField = someCarField;
        this.anotherCarField = anotherCarField;
    }
}

This is a class that contains both Entities.

Then you would need a factory to properly create the DTO:

/**
 * This is a Factory class which creates a VehicleDTO
 */
public class VehicleDTOFactory {

    public VehicleDTO createVehicleDTO(CarEntity car, TruckEntity truck){
        return new VehicleDTO(truck.getSomeTruckField(),
                truck.getAnotherTruckField(),
                car.getSomeCarField(),
                car.getAnotherCarField());
    }

}

Then over the MVC controller you would call the factory Method and fill the parameters with Entities from your database.

This is just a very basic example.

I'd recommend looking closer into why Factories and DTOs are used

Related