Using Hibernate to Join to Tables
I am creating an application where people will be able to post comments or articles, and users will be able to rate whether or not the article was helpful to them or not.
I currently have two Entities that look like this (non-pertinent details omitted):
Article.java
@Entity
Article
@Id
private int article_id
@ManyToOne
@JoinColumn(name="user_id")
private User user;
User.java
@Entity
User
@Id
private int user_id
I want a way to know whether or not a user has "voted" on an article for two reasons, 1. to not let them vote twice, 2. to suggest other articles which may be helpful.
I've experimented with a @OneToMany
r开发者_C百科elationship in each object with a Cascade option each reference in Article and User to update the object I called User_Article
(which has just two columns, article_id and user_id), however, I keep getting a LazyInitilizationException
when the cascade happens?
I'm looking to any hibernate gurus to guidance on both implementation and architecture on this problem.
Try
@OneToMany(fetch=FetchType.EAGER)
However, it is good to avoid eager loading of large collections. That's why leave it lazy, and initialize it using Hibernate.initialize(..)
only whenever you are sure you will need it. Or use an HQL query like:
SELECT entity FROM Entity entity JOIN entity.collection
精彩评论