tags:

views:

44

answers:

1

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 relationship 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.

+1  A: 

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
Bozho
@Bozho, thanks for your response. I'll add that to my code, however, from your perspective, architecturally, is this a good way to handle my situation? I'm thinking this may be overkill, however, I cannot find a good enough reason why.
El Guapo
see my update..
Bozho
Thanks! I was getting a bit hung up on the session aspect of the application. I guess what I'll do is update the collection of "votes" right before the service-layer returns to my controller.
El Guapo