How to handle bidirectional relationships when constructing hibernate entities?

扶醉桌前 提交于 2019-12-04 11:08:59

In our projects we usually try to avoid bidirectional associations.

One reason is that you have a cycle in your model that may create problems if you want to somehow serialize it, for example let's say you want to serialize an Account and your serialization algorithm is not smart enough you end up with an infinite loop (because Group has a reference back to the Account).

Second reason is that I find it clearer having only one way to navigate the model. What I usually do is to remove the OneToMany association in the Account entity and use a repository call when I need to collect all the Groups for a specific Account (but this probably depends on your use case and personal taste).

Third, if you get rid of the addToAccount method and you use field access you can make your classes immutable that is a good thing.

In my experience you're doing it exactly as it is commonly done. My question would be more about the structure (I expect there is a lot more going on than the sample provided above) as to why you want to manipulate the Account directly from the Group.

I also question whether this is a OneToMany or a ManyToMany situation (usually multiple accounts can belong to a single group and multiple groups can belong to a single account but it is all in the semantics of your particular accounting scheme...) anyway: you're doing it right, and though I question (in this exact case) why you would want to directly manipulate the account (unless it is Lazily loaded) this is entirely fine.

[You may need to add some Cascade rules so that it persists properly depending on your configuration.]

You should note that by mapping to the Account you have effectively added it to the List of the Account. When the database next queries to create that list it will populate the list by finding the references from the Account entity.

In short->

public void Group.setAccounts(Account a)
{
  this.account = a;
}

is effectively equivalent to what you are doing above. The database will query and populate the List with something akin to:

//Pseudo SQL
    SELECT g.id FROM Group g WHERE g.account_id = :account_id

Thus, aside from the lazy load (something you may or may not want) adding to the groups is unnecessary as the List is defined by the query.

(Don't make it too hard, it look simple. I hope the long explanation gives you an idea of what's happening in the JPA)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!