Reputation: 725
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?
Upvotes: 0
Views: 43
Reputation: 1533
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.
Upvotes: 1