使用Hibernate联接表 [英] Using Hibernate to Join to Tables

查看:74
本文介绍了使用Hibernate联接表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个应用程序,人们可以在其中发布评论或文章,并且用​​户可以评估文章是否对他们有帮助.

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

我想要一种方法来了解用户是否对文章进行了投票",其原因有两个:1.不要让他们投票两次; 2.建议其他可能有帮助的文章.

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.

我已经在每个对象中使用Cascade选项尝试了@OneToMany关系,文章和用户中的每个引用都更新了我称为User_Article的对象(只有两列,article_id和user_id),但是,我在级联发生时继续得到LazyInitilizationException吗?

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.

推荐答案

尝试

@OneToMany(fetch=FetchType.EAGER)

但是,最好避免急于加载大集合.这就是为什么要让它保持懒惰,并且仅在确定需要时才使用Hibernate.initialize(..)对其进行初始化.或使用类似以下的HQL查询:

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

这篇关于使用Hibernate联接表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆