使用JPA获取公司的所有员工详细信息

时间:2019-03-10 09:54:09

标签: mysql spring java-8 spring-data-jpa jpa-2.0

我有以下关系。我正在使用Spring JPA 2和MySQL数据库

enter image description here

公司实体

@Entity
@Table(name = "company")
public class Company {

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    @Column(name="id", length = 45)
    private String id;

    @Column(name = "name")
    private String name;

    @Column(name = "address")
    private String address;

    @OneToMany(mappedBy = "company", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JsonManagedReference
    private List<Department> departments = new ArrayList<>();

    // How to get bring all the employees over here
    private List<Employee> employees = new ArrayList<>();

    public Company() {

    }

    :
    //getters and setters
}

部门实体

@Entity
@Table(name = "department")
public class Department {

    @Id
    @GeneratedValue(generator = "id")
    @GenericGenerator(name = "id", strategy = "uuid")
    @Column(length = 32)
    private String id;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(referencedColumnName="id", name = "company")
    @JsonBackReference
    private Company company;

    @Column(name = "name")
    private String name;

    @OneToMany(mappedBy = "department", cascade = CascadeType.PERSIST, fetch = FetchType.LAZY)
    @JsonManagedReference
    private List<Employee> employees = new ArrayList<>();

    public Department() {

    }

    :
    //getters and setters
}

员工实体

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

    @Id
    @GeneratedValue(generator = "uuid")
    @GenericGenerator(name = "uuid", strategy = "uuid")
    @Column(name = "id", length = 45)
    private String id;

    @Column(name = "name")
    private String name;

    @Column(name = "age")
    private int age;

    @Column(name = "position")
    private String position;

    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinColumn(referencedColumnName = "id", name = "department")
    @JsonBackReference
    private Department department;

    public Employee() {

    }
    :
    //getters and setters
}

公司实体中,如何获得如下所示的所有员工列表

private List<Employee> employees = new ArrayList<>();

我为变通办法所做的

我已经实现了公司与员工之间的一对多关系,这样我就可以从公司获得所有员工。但是我觉得这种方法违反了RDBMS规范化。我认为无论如何,员工与部门有关系,部门与公司有关系,因此我们可以使用此关系获取公司实体中的所有员工详细信息列表。如果我在任何地方都不对,请纠正我。

我们又如何在Company实体中定义它而不将任何与Company相关的列放在Employee实体中

0 个答案:

没有答案