Issue
I have two tables, joined each other. How I can get from database both of them using Spring data jpa?
Code as below,
@Entity
@JsonNaming(PropertyNamingStrategies.UpperSnakeCaseStrategy.class)
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String phone;
@Enumerated(EnumType.STRING)
private Position position;
private BigDecimal salary;
@OneToOne(mappedBy = "employee", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private Car car;
}
@Entity
@JsonNaming(PropertyNamingStrategies.UpperSnakeCaseStrategy.class)
public class Car {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String model;
private String color;
private double price;
@OneToOne
@JoinColumn(name = "employee_id")
private Employee employee;
}
// my serice:
@Override
public Employee findEmployeeByName(String name) {
return employeeRepository.getEmployeeByName(name);
}
result: result
Solution
As you already had specified fetchType Eager, whenever you fetch any of the object car or the employee you will get all the data of both the corresponding objects.
Answered By - yoyo yo
Answer Checked By - Timothy Miller (JavaFixing Admin)