'How get two joined tables from database in Spring Jpa?
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 1:[1]
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.
Solution 2:[2]
could you please explain what do you want exactly ? like If you want just to use both tables in a query that returns a one of your tables (exemple the cars by employee's name) there is no problem. But if you want to return columns from both tables you can have a look at this answer stackoverflow.com/a/47301366/14994239 it shows how to handle this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | yoyo yo |
| Solution 2 | hakima maarouf |
