0

In Hibernate, you can specify a one-to-many or it's inverse many-to-one via @OneToMany or @ManyToOne annotations, respectively. But in the examples I see, every time you relate A to B, you need to also relate B to A. For instance, if Teacher has a one-to-many relation with Course (a teacher can teach many courses), do I need to:

teacher.getCourses().add(mathCourse);
teacher.getCourses().add(historyCourse);

as well as:

mathCourse.setTeacher(teacher);
historyCourse.setTeacher(teacher);

Or is it sufficient to just relate them one-way (and thus allow you to pick one of the above sets of relations)? In other words, could I just relate them via:

teacher.getCourses().add(mathCourse);
teacher.getCourses().add(historyCourse);

Why/why not? Thanks in advance!

  • For example, as long as `mathCourse` is a persisted entity, you only need to add it on one side of the relationship. Also, you don't necessarily need bidirectional relations. – Sotirios Delimanolis Jul 25 '13 at 03:05

1 Answers1

0

You can add only uni-directional relationship in that case. See the sample below

@Entity
@Table(name = "contact")
public class Contact implements Serializable {

 

 @ManyToOne
         @JoinColumn(name = "companyId")
           private Company company;

      ...       }  

@Entity
@Table(name = "company")
public class Company implements Serializable {
 
  @ManyToOne
  @JoinColumn(name = "statusId")
  private CompanyStatus status;
   
  ...
   
 }
sk85
  • 407
  • 4
  • 17
  • Thanks @vicky (+1) - can you help explain the difference between uni-directional and bi-directional relationships here? What's the benefits of both, and how do both affect the underlying table structures? Thanks again! –  Jul 25 '13 at 16:56
  • Bidirectional relationship provides navigational access in both directions, so that you can access the other side without explicit queries. Also it allows you to apply cascading options to both directions. Please check this, [link]http://powerdream5.wordpress.com/2007/10/18/uni-directional-or-bidirectional/[link] – sk85 Jul 26 '13 at 04:36