I am still not a stage where I feel completely comfortable with JPA.
Right now I am torn between using relationship annotations or simply retrieving the related objects when I need them with queries.
For instance I have a User who owns Projects. I can use a onetomany relationship and retrieve the projects in an object fashion way OR I can simply query the user’s projects when I need them.
The latter solution involves more code but somehow I have more freedom and control over what I want to do, or at least it is my impression. The former will obviously take care of quite a fair amount of boiler plate code such as create/delete/update of objects, but there are quite a few tricks to learn along the way.
I would greatly appreciate if someone could come up with a simple rule of thumb on when to use relationship annotations in JPA, preferably based on her/his experience.
Thanks,
Thomas
The basic rule is that you should create a relationship when you need it.
For one-to-one and many-to-one relationships it’s quite easy: you need them almost always. For example, when you display
Projectinformation you almost always need to display its owner information as well, thus creating a relationship is a good choice here.One-to-many and many-to-many relationships require more care, since overuse of them can cause performance problems.
My personal rule of thumb is the following: if you don’t need to display all
Projects ofUserat once without pagination or filtering (or at least don’t need to do it often), don’t create a relationship. Otherwise you can create it (for example, you usually need allOrderLines ofOrderat once, thus you need a one-to-many relationship in this case).