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?