1
votes

I understand the general difference between the two JPA annotations for JoinColumn and mappedBy, and that a oneToMany relationship should use mappedBy. I understand this is to ensure that hibernate (or whatever JPA tool I'm using) recognizes a bidirectional relationship, instead of two unidirectional relationships that happen to share columns.

However, I'd like a better understanding of why that matters? I presume that recognizing a bidirectional relationship allows for more optimal storing or fetching of the data, but could someone give me an example of how? If I have a Parent object with many Children objects and I annotate it with a JoinColumn instead of the preferred mappedBy where will I suffer a performance penalty over using mappedBy?

2

2 Answers

2
votes

I was practicing @joincolumn and mappedBy both, and here is what I found when I was analysing hibernate logs.

Performing Save operation using mappedBY

When you create entities using mappedBy, you create the parent object in your child object too, and then perform save operation. What hibernate does in the back background :-

  1. Perform insert operation on parent object
  2. Perform insert operations on child object. Set foreign key reference of parent object at the time insertion only

Performing Save operation using @JoinColumn

When you create entities using @JoinColumn, you do not create the parent object in your child object. What hibernate does in the back background :-

  1. Perform insert operation on parent object
  2. Perform insert operations on child object
  3. Perform separate update operations to update foreign key reference on all child object

You can see these operations in your hibernate logs.

Basically @JoinColumn does the same job as mappedBy with extra Update operations. So, definately performance of mappedBy is better than @JoinColumn.

However, it will not impact if you create one or two entities, but it will definately cause a significance performance issue if we have to create a large amount data.

0
votes

This answer should as comment , But I can not add comment since I don't have enough reputations.Refer to JPA JoinColumn vs mappedBy