简体   繁体   中英

What is the best practice for sending data to the client: returning an entity or a dto?

I'm not sure whether I should send the entity which has the selected table and all the tables related to it or a DTO that has the foreign key to the related tables and only call said tables when needed.

Example of entity returned:

@Entity
public class Staff implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id; 
    private String name;
    private String role;    
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn()
    private Gsm gsmDetails; 
    @OneToMany(mappedBy ="staff", fetch = FetchType.LAZY)
    private List<Coupon> coupons = new ArrayList<Coupon>(); 
    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn()   
    private Voip voip;
    @OneToOne()
    private Card card;
    @OneToOne()
    private Phone phone;
//rest of the getters setter and consturctors

Example of a DTO:

public class staffDto {
    
    private Long id; 
    private String name;
    private String role;    
    private Long gsmId; 
    private List<Long> couponID; 
    private long voipID;
    private long cardId;
    private long phoneId;

I don't know the best approach to not cause unnecessarily long loading times or bloating.

Purely from my point of view and opinion, I would recommend DTO .

In most cases, we want to hide the database structure.

I'm definitely not an expert on this topic and I'm more of a frontend - angular developer. Nevertheless, I think this one point answers your question.

Here I am sending a link to a similar question, where it is beautifully explained why to prefer DTO over enitities.

https://stackoverflow.com/a/49914242/8366174

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM