【发布时间】:2013-07-23 22:31:10
【问题描述】:
我有两个表:“publication”和“publication_translations”。
在休眠中,我使用注释将翻译映射到带有@ManyToOne 的发布对象。
在 DAO 层中,我使用查询来获取所有发布,如下所示:
from publication p where application_id = :applicationId
现在我想将翻译加入到应用程序对象中,例如:
from publication p left outer join fetch p.translations pt where application_id = :applicationId
这会产生如下 SQL 查询:
select
publicatio0_.id as id25_0_,
translatio1_.id as id26_1_,
publicatio0_.application_id as applica17_25_0_,
publicatio0_.url as url25_0_,
translatio1_.language as language26_1_,
translatio1_.name as name26_1_,
translatio1_.publication_id as publicat4_26_1_,
translatio1_.id as id0__
from
publication publicatio0_
left outer join
publication_translation translatio1_
on publicatio0_.id=translatio1_.id
where
and application_id=180;
当我直接在 MySQL 中运行此查询时,它会按预期返回行。但是 session.list() 返回的 List 以某种方式保持为空。
当翻译不存在时,Hibernate 似乎会丢弃行。 (正如您对内连接的期望,但不是左外连接..
为什么会这样?我错过了什么吗?
顺便说一句。我这样做的原因是因为我想在声明特定语言的 hql 子句中添加 where 或 with,这样您就可以获取特定语言的翻译。但我简化了案例来说明问题。最终结果将类似于:
from publication p join fetch p.translations pt where (pt.language = :language or pt.language is null) and application_id = :applicationId
Publication.java:
@OneToMany(mappedBy = "publication")
private List<PublicationTranslation> translations;
PublicationTranslation.java
@ManyToOne
private Publication publication;
编辑:在类上添加注释: Edit2:在 Publication.java 上的注释中更改错误
【问题讨论】:
-
您的查询对我来说很好。您能否发布您的
@OneToMany和@ManyToOne映射。另外,为了确定,select p from publication p left join fetch p.translations pt where p.application_id = :applicationId做得更好吗? -
不,我尝试使用“select”、“left join”、“join fetch”和没有“fetch”。
-
为什么是 session.list()?我想你会得到一个发布对象并通过调用publication.getTranslation()来检索翻译
-
那么,您是通过主键列加入的吧?外键类似于
ALTER TABLE publication_translation ADD FOREIGN KEY (id) REFERENCES publication (id)? -
@Hippoom:我想要一份正确语言的出版物列表。不是一个对象。