Home > Back-end >  How get two joined tables from database in Spring Jpa?
How get two joined tables from database in Spring Jpa?

Time:04-11

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

CodePudding user response:

Whenever you fetch one entity from the database by default the related entities will come automatically because of mapping. This is handled by JPA automatically in the background.

CodePudding user response:

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.

CodePudding user response:

As you have already mentioned FetchType.EAGER, when you fetch any one of Employee or Car objects from the database, Car or Employee that is associated with other respectively will also be fetched and you can use them by calling field property or in GET method you will get other object embedded in Employee JSON object.

  • Related