0

Given two entities Employee and EmployeeAddress, I am trying to implement the DTO pattern - mainly because my IDE shows a warning when using an entity as parameter in my REST controller.

In this context, I have a question regarding how to deal with the OneToOne relationship between these two entities:

The parent entity:

@Entity
@Table
public class Employee{

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

    private String firstName;
    private String lastName;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "employee_address_id")
    private EmployeeAddress employeeAddress;

}

The child entity:

@Entity
@Table
public class EmployeeAddress{

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

    private String street;
    private String postalCode;

    @OneToOne(mappedBy="employeeAddress")
    private Employee employee;

}

My first idea was to introduce the following two DTOs:

@Getter
@Setter
public class EmployeeDTO {
    private Long id;
    private String firstName;
    private String lastName;
    private EmployeeAddressDTO employeeAddress;
}

@Getter
@Setter
public class EmployeeAddressDTO {
    private Long id;
    private String street;
    private String postalCode;
}

This doesn't seem to work, however: I have to replace the EmployeeAddressDTO inside my EmployeeDTO with the actual entity EmployeeAddress in order for this to work. This, however, seems a bit contradicting to me - why would I create an EmployeeDTO only for it to contain an entity?

So, I wonder, how do I deal with this OneToOne relationship in my DTO? Do I have to create an EmployeeDTO as:

@Getter
@Setter
public class EmployeeDTO {
    private Long id;
    private String firstName;
    private String lastName;
    private String street;
    private String postalCode;
}

Would this be the right approach?

Luk
  • 1,009
  • 2
  • 15
  • 33

1 Answers1

0

why would I create an EmployeeDTO only for it to contain an entity?, that is the whole question about DTOs.

In small or toy apps there may even no point for DTOs anyway. When your app is growing, things are different. It is good practice to separate the persistence (entities) from the presentation (or API, or interface to the outside world).

Entities defining the app data model (the data that needs your app to do the work), DTOs are what you want to export (in a controlled way) to the world.

Of course, at the beginning it is mostly the same data.

PeterMmm
  • 24,152
  • 13
  • 73
  • 111