Hibernate Query Collection,它也有一个映射实体

时间:2015-01-20 20:28:12

标签: hibernate jpa

工作实体

 @ManyToMany
 @NotFound(action = NotFoundAction.IGNORE)
 @JoinTable(name="JOB_ACTIVITES", joinColumns=@JoinColumn(name="jobId"),
            inverseJoinColumns=@JoinColumn(name="an"))
 private Collection<Activity> activities;

活动实体

@OneToOne(fetch = FetchType.LAZY)
@JoinColumns(value = { @JoinColumn(name = "dwgNo", referencedColumnName = "dwgNo"), @JoinColumn(name = "rev", referencedColumnName = "rev") })
private Drawing drawing;

查询

public List<Activity> getActivitiesByJobId(Long jobId) {
    String criteria = "SELECT jb.activities FROM Job jb WHERE jb.jobId=:jobId";
    List<Activity> activities = em.createQuery(criteria).setParameter("jobId", Long.valueOf(jobId)).getResultList();
    return activities;
}

错误

javax.el.E​​LException:/job.xhtml value =&#34;#{activity.drawing.dwgNo}&#34;:org.hibernate.LazyInitializationException:无法初始化代理 - 没有会话

我理解错误,但我不知道如何修改我的查询以加入Drawing实体。

这样的东西
SELECT jb.activities FROM Job jb LEFT JOIN FETCH Drawing ON
ACTIVITY.dwgNo=Drawing.drwNo WHERE jb.jobId=:jobId";

但该语法更像是原生SQL。如何指定集合上的路径?

1 个答案:

答案 0 :(得分:1)

Hibernate已经知道了,感谢关联的映射,它们如何映射和链接在一起。所以它不需要任何ON子句。 您可以为每个连接的关联分配别名,以便进一步加入或表达标准:

select activity from Job job 
inner join job.activities activity
left join fetch activity.drawing
where job.jobId = :jobId