2

I have doubt which one can I use uni/bi directional assications. Hibernate was recomended to use bidirecitonal assoicatation Best Practies. But some of people answered to use uni directional assoications.

What are the best practices of associations and collections?

IonicMan
  • 743
  • 1
  • 12
  • 31
tech2504
  • 947
  • 4
  • 19
  • 34

1 Answers1

3

There is no absolute best practice. Use a bidirectional association when you want or need a bidirectional association, and a unidirectional when you want it unidirectional.

Some associations should not be bidirectional. For example, if an address can be an address of a user, or a consumer, or a vendor, or a contact, or whatever, having a reference to each of these entities in the address (all null except one) isn't a wise choice.

Other than that, when two entities are tightly coupled, I generally make the association bidirectional to ease the development and the writing of the queries (as the Hibernate documentation says).

I also agree with the SO answer you linked to: be careful when you have a One to Very Many or Many to Very Many association. But this association, if it's not the owner side, can also stay completely private to the entity (and thus never be loaded), just to help writing queries, but forbidding initializing the very large collection.

To have no problems with JPA, you "just" need to understand and think about what happens under the cover. When developing, turn SQL logging on and look at the queries being executed.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • " can also stay completely private to the entity (and thus never be loaded), just to help writing queries, but forbidding initializing the very large collection" You mean using a private getter ? (offtopic: it's always a pleasure to read your answer JB) – Gab May 22 '13 at 13:27
  • Yes, or no getter (and no setter) at all if the annotations are on fields. Thank you for the kind words. – JB Nizet May 22 '13 at 13:29
  • Thanks.I missed one question i., Why eclipse/net beans tools are generated bi-directional associations?Even they aren't gave chance to implement other list,set collections. – tech2504 May 22 '13 at 16:41
  • I never use the automatic generation tools of the IDEs. I generate my code by myself. – JB Nizet May 22 '13 at 17:04