简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM