How to use Hibernate annotations @ManyToOne and @OneToMany for associations

后端 未结 1 1281
情话喂你
情话喂你 2020-12-15 03:13

I am learning Spring, Hibernate, Maven by using this tutorial: Chad Lung: A project using Netbeans 7, JUnit, Maven, HSQLDB, Spring and Hibernate. It works ok but I need to m

相关标签:
1条回答
  • 2020-12-15 04:02

    What's wrong is the following:

    @OneToMany(fetch = FetchType.LAZY)
    @JoinColumn(name="idEmployees")
    public List<Task> getTasks() {
        return tasks;
    }
    

    And it's wrong for two reasons.

    1. @JoinColumn(name="idEmployees") means: this OneToMany is mapped using a join column (i.e. a foreign key) named idEmployees. But the join column is not named idEmployees. idEmployees is the primary key of the Employee table. The join column name is TasksIdEmployees. Putting the right name would make the mapping correct for a unidirectional OneToMany association. But the association is bidirectional, which leads to the second reason...

    2. In a bidirectional association, there is no need (and it's a bug) to repeat the mapping information on both sides of the association. One side (the many side) must be the owner of the association and define the mapping. The other side must be the inverse side by simply saying: go see at the other side how this association is mapped. This is done using the mappedBy attribute, which tells Hibernate the name of the field or property on the other side which is the owner of the association:

      @OneToMany(mappedBy = "employee")
      public List<Task> getTasks() {
          return tasks;
      }
      

    Note that LAZY is the default for toMany associations, so it's unnecessary to specify it.

    0 讨论(0)
提交回复
热议问题