Question

I have done a lot of googling but still I don't understand why should I use association in hibernate? I manage to do things without mentioning one-to-many or any other association. I can always do the Cartesian product on tables using some join condition without explicitly using hibernate joins. What will I miss if I don't use them? Please tell advantages or disadvantages of them if any. Thank You.

Was it helpful?

Solution

The main advantage of associations in Hibernate is that they allow you to access/persist child or parent entities easily via your source code. For example if I had the following:

@Entity
public class Student{

   @OneToMany
   private List<Course> courses = new ArrayList<Course>();

   //Accessors
}

Within my code I could use the association to fetch all courses for a student such as:

Student student = studentRepo.findById(1, Student.class);
List<Course> courses = student.getCourses();

That is all that is necessary to traverse this parent child relationship. No additional SQL or join required. You can also perform other crud operations such as insert and delete easily.

BTW You mention Cartesian joins in your original question, these should be the exception and not the norm. They can carry significant performance overhead and can be often accomplished more efficiently using a different join.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top