0

I have two table with many-to-one relationship. Example is, I have Office table and Employee table. One Employee belong to one Office and one Office belong to many Employee.

Office

@Entity(name = "office")
@Table(name = "office", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Office {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "office_name", nullable = false)
    private String officeName;
}

Employee

@Entity(name = "employee")
@Table(name = "employee", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Employee {

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

    @Column(name = "employee_name", nullable = false)
    private String employeeName;

    @ManyToOne(cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JoinColumn(name = "office_id", referencedColumnName = "id", nullable = false)
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private Office office;
}

OfficeDto

public class OfficeDto {

    private Long id;
    private String officeName;
}

EmployeeDto

public class EmployeeDto {

    private Long id;
    private String employeeName;
    private OfficeDto office;
}

With above way of defining the entity and the DTO, when I do employee.findAll(), the JSON result is also include the detail of the office data.

Is there any way that I could achieve (objective):

  1. When do saving new employee, I just have to mention the id of the office.
  2. When do findAll employee, I could choose whether I want to gove the id only or also with the entire object to the client.

Because, with current situation, I think I need to define two employee DTO. First one is contain the entire office data (like the code of EmployeeDto) and the second one is replace private OfficeDto office with private int office.

Akza
  • 1,033
  • 3
  • 19
  • 37
  • Add `@JsonIgnore` in place of `@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})`. Then, in your JSON response of **Employee** you won't find **Office** data. When you save a new Employee you have to assign a new Office to **office** property or find the existing Office by its id and assign it instead. To achieve your 2nd objective you will have to use **projections**. – Johna Jul 05 '19 at 09:07

1 Answers1

1

The second problem you can solve by projection : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections Or just specific mapper to DTO, for mapping you can use mapstruct : http://mapstruct.org/documentation/installation/

For the first problem i found some answer in stack, but you need verify it : JPA many-to-one relation - need to save only Id

Sebastian
  • 92
  • 2
  • 14