Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it alway necessary to have both @oneToMany and @manyToOne for a relationship in hibernate?

I have this question, let's suppose we have teacher and student entity, one teacher has many students, and I only need to get the students info including their teacher, I'll never need to get the teacher with the list of students.

Having that hypothetical scenario, is it necessary to have in the Teacher entity an attribute to map Students and annotate it with @oneToMany, and in the Student entity to have an attribute to map the teacher and annotate it with @ManyToOne ?, Or is it enough just having an attribute to map the teacher and annotate it with @manyToOne in the Student entity? This way avoiding having an unnecessary attribute to map Students in the teacher entity.

Thanks a lot in advance.

like image 908
Juliancho9191 Avatar asked Oct 26 '25 12:10

Juliancho9191


1 Answers

Bidirectional one-to-many and both many-to-one association mappings are fine. But you should avoid unidirectional one-to-many associations in your domain model. Otherwise, Hibernate might create unexpected tables and execute more SQL statements than you expected.

like image 156
rajnikant7008 Avatar answered Oct 29 '25 00:10

rajnikant7008



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!