3

I have two tables department and employee, and a department can have many employees.

If I have to model employee table in database using hibernate by making departmentId as the foreign key, I have two options available.

a) I can either create a list in Department class

b) Using @ManyToOne and @JoinColumn on referencedColumnName='departmentId' in Employee class.

Which approach is recommended? Or are these two approaches used for completely different problems?

working
  • 873
  • 3
  • 11
  • 21

1 Answers1

5

First there are two entities present here department and employee. Second, we have to understand what ManyToOne means here, as you said, many employees could be there in a single department.

Mapping would be like, please note that this a snippet only:

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


@Id
@GeneratedValue
@Column(name="employee_id")
private Long employeeId;

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

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

@ManyToOne
@JoinColumn(name="department_id")
private Department department;
// Getter and Setter methods

}

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


@Id
@GeneratedValue
@Column(name="department_id")
private Long departmentId;

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

@OneToMany(mappedBy="department")
private Set<Employee> employees;

// Getter and Setter methods

}

Since there is a bi-directional relationship here one side would be a owner of the relationship here. The annotation @JoinColumn indicates that this entity is the owner of the relationship. That is, the corresponding table has a column with a foreign key to the referenced table, whereas the attribute mappedBy indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity.

More on what does mapppedby do can be found here.

Community
  • 1
  • 1
Sandeep B
  • 765
  • 1
  • 6
  • 19
  • I have exactly the same structure in my application. But when I try to insert an employee with a department Id that is not present in the department table it does not give me an error. It should in fact give me an error saying that foreign key does not exist. – working Jul 28 '14 at 13:06
  • I think your foreign key constraint is not correct, i get this exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Column 'department_id' cannot be null. Please check your constraints and also that department_id should not be allowed null values, etc. – Sandeep B Jul 29 '14 at 05:47
  • Although the mapping was correct, i figured out that both the tables were created using different engines. One that was created by me had MyISAM engine and another had innodb by hibernate default. So hibernate was failing to add foreign key constraint even though the mapping was correct. – working Jul 31 '14 at 04:01