Search code examples
springspring-boothibernateentitydto

is using DTOs in every case always a good practice?


Imagine i have an entity like this:

@Entity
@Getter
@Setter
@ToString
@Table(name = "employeeSalary")
public class EmployeeSalary{

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;

@Column(name = "fullName", nullable = false, length = 60)
private String fullName;

@Column(name = "salary", nullable = false)
private double salary;

@Column(name = "month", nullable = false)
@Enumerated(EnumType.STRING)
private Month month;

@Column(name = "year", nullable = false)
private Year year;

}

Now imagine i created DTO like this:

@Data
@NoArgsConstructor
@AllArgsConstructor
public class EmployeeSalaryDTO {
private String fullName;
private double salary;
private Month month;
private Year year;
}

The Question is following: is creating DTO in this case really a good practice? as we can see both DTO and entity is the same (the only difference is that DTO does not have id, but lets imagine adding id also in this DTO) does it make any sense to create this DTO. Because as i know its not a good idea to manipulate entity in service layer, its a better option to manipulate DTO and then convert this DTO to entity, but as we see DTO and entity are identically the same, so does it make any sense to create DTOs when we have 100% similarity in these two classes? Or is it a good practice to create them anyway? (because manipulating entity in service layer is not a good idea, better is to manipulate dto and then convert to entity)


Solution

  • So its a good practice to introduce another layer as DTO. Because manipulating data and operations on entity seems not a good practice. A good idea would be have manipulation of data in DTOs and then converting them to entity's using model mapper. So in a word its a good practice to have DTO even though we have exactly the same fields in entity and DTO.