Hibernate Storing Fields inside Classes

孤人 提交于 2020-01-06 17:08:22

问题


I have two classes with two individual tables, "Employee" and "Company". I would like to keep a list of employee inside Company class. It is easy but I do not know how to represent this list in the database side.

Class 'Company':

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

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

    private List<Employee> employeeList;

}

Class 'Employee':

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

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

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

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

Without hibernate, I would choose the design creating another table with two columns 'employeeId' and 'companyId' and try to get all employees with the 'employeeIds' matching a 'companyId'. I do not know if it is possible to do same in hibernate or not. If so how? If not, what is your solution?


回答1:


The short answer is that you can configure Hibernate to generate a thirty table to store the association as you wish. You can achieve this using @JoinTable annotation. Following your example it will be something like:

@Entity
@Table(name = "company")
public class Company {
...
@OneToMany// or @ManyToMany
@JoinTable(name = "table_name",
    joinColumns = @JoinColumn(name="employeeId", referencedColumnName="id"),
    inverseJoinColumns = @JoinColumn(name="companyId",  referencedColumnName="id"))
private List<Employee> employeeList;

Now Hibernate will create a table named table_name with the two columns that you want and the correspondoning foreign key constraints to the tables employee and company. You can specify the freign keys names using the @ForeignKey annotation too.




回答2:


I think you need to implement oneToMany relationship between Company and Employees. Hibernate @OneToMany annotation can be used for the same .

Here is the example which shows how to do that in Hibernate



来源:https://stackoverflow.com/questions/30687060/hibernate-storing-fields-inside-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!