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.
- User has a @OneToMany List and @OneToMany List.
- Post has @ManyToOne User, @OneToMany List, @ManyToMany开发者_如何转开发 List.
- Comment has @ManyToOne List, @ManyToOne User.
- Tag has @ManyToMany List.
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.
I think some of them should be unidirectional.
For example, in real-world scenario you usually don't need to display "all Post
s by User
", because they should be filtered or paginatied, so you need to run queries against the database instead of retrieving Post
s 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 Post
s in User
makes no sense. The same is true for User
- Comment
and Tag
- Post
relationships.
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.
精彩评论