Marc-François
Marc-François

Reputation: 4060

Is it OK to have only bidirectional relationships with Hibernate?

So the question is pretty much in the title.

Let's say I have some classe: User, Post, Comment and Tag.

I'm new to Hibernate, but I find it easy then to use for example the attributes of a Tag object to get all the Post objects related to that tag, or find the author of a Post object or all the Post written by a certain User.

Is it OK ?

I'm talking more in terms of performance here. I'm also using the Play! framework. I don't know if this changes anything.

Upvotes: 1

Views: 464

Answers (2)

hvgotcodes
hvgotcodes

Reputation: 120268

It is ok to have bidirectional relationships. The real danger is in also having lazy false, because then you will end up loading a lot of your db into memory for every request.

If you have bidirectional relationships, it is good practice to create specific dao methods that allow you to load only the data you need, with hql.

Upvotes: 2

axtavt
axtavt

Reputation: 242726

I think some of them should be unidirectional.

For example, in real-world scenario you usually don't need to display "all Posts by User", because they should be filtered or paginatied, so you need to run queries against the database instead of retrieving Posts from the User (because not filtering a collection at the database side in these use cases can be a real performance problem, especially if that collection is huge).

Therefore having collection of Posts in User makes no sense. The same is true for User - Comment and Tag - Post relationships.

Upvotes: 2

Related Questions