JPA存储库更改,以便从两个表合并中获取数据

时间:2019-02-18 17:43:45

标签: sql spring-boot jpa spring-data-jpa

我有2个表Employee和Branch

  employee (
       emp_id INT PRIMARY KEY,
       first_name VARCHAR(40),
       last_name VARCHAR(40),
       birth_day DATE,
       sex VARCHAR(1),
       salary INT,
       super_id INT,
       branch_id INT
  );

   branch (
        branch_id INT PRIMARY KEY,
        branch_name VARCHAR(40),
        branch_address VARCHAR(50),
        branch_pincode INT
    );

我有一个查询(从员工A的分支B中选择A.emp_id,A.first_name,A.last_name,A.birth_date,B.branch_id,B.branch_name,B.branch_address,B.branch_pincode,其中A.branch_id = B.branch_id;)

我有两个实体employee_repo和branch_repo接口,它们扩展了CrudRepository。 我将如何从这些存储库合并的查询中获取数据。

 @Entity
 @Table(name = "employee")
 public class Employee {

     @Id
     @GeneratedValue(strategy=GenerationType.TABLE)
     private Integer emp_id;

     private String first_name;
     private String last_name;
     ..
     ..
     //

     // with getters and setters...
  }

 @Entity
 @Table(name = "branch")
 public class Branch {

     @Id
     @GeneratedValue(strategy=GenerationType.TABLE)
     private Integer branch_id;

     private String branch_name;
     private String branch_address;
     ..
     ..
     //

     // with getters and setters...
  }

我已经尝试过了,但是无法解决问题

 @Entity
 @Table(name = "employee")
 public class Employee {

     @Id
     @GeneratedValue(strategy=GenerationType.TABLE)
     private Integer emp_id;

     private String first_name;
     private String last_name;
     ..
     ..
     //

     // with getters and setters...
     @OneToOne(mappedBy = "branch", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
     private Branch branch;

  }

 @Entity
 @Table(name = "branch")
 public class Branch {

     @Id
     @GeneratedValue(strategy=GenerationType.TABLE)
     private Integer branch_id;

     private String branch_name;
     private String branch_address;
     ..
     ..
     //

     // with getters and setters...

     @OneToOne
     @JoinColumn(name = "branch_id", referencedColumnName = "branch_id")
     private Employee employee;
  }

0 个答案:

没有答案