java 使用内部联接的简单 hql 命名查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7914075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 21:59:44  来源:igfitidea点击:

Simple hql named query that uses a inner join

javahibernatehqlinner-join

提问by NimChimpsky

I want to do something like this in my domain/entity object :

我想在我的域/实体对象中做这样的事情:

@Entity
@NamedQueries({
@NamedQuery(name="favouriteCats", query="from Cat c inner join on UserCat uc where uc.isFavourtie = true and uc.user = :user")
})
public final class Cat extends BaseTable

So that in my service layer I can do this :

所以在我的服务层我可以这样做:

Query query = session.getNamedQuery("favouriteCats")
query.setParameter(0, MyUser);
return query.list();

However, my syntax in HQL is incorrect - and aftern ten minutes looking at official docs I have decided to give up and ask here ... ? My usercat table is joined like so :

但是,我在 HQL 中的语法不正确 - 看了十分钟的官方文档后,我决定放弃并在这里问......?我的 usercat 表是这样加入的:

@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="cat_fk", insertable=false, updatable=false)
private cat

The sql is this, it works fine at my db command prompt:

sql 是这样的,它在我的 db 命令提示符下工作正常:

select c.* 
from cat as c inner join usercat as uc on c.id = uc.cat_fk 
and uc.isFavourite = 1 //bit field
and uc.user_fk = 74 //just user id

Is it just me or is the hibernate documentation rather painful, and do you find yourself often wondering whether it would be quicker just to write normal jdbc prepared statements to populate your pojos/domain objects/dto's... ?

是我还是 hibernate 文档相当痛苦,您是否发现自己经常想知道仅编写普通的 jdbc 准备好的语句来填充您的 pojos/域对象/dto 是否会更快...?

回答by col

I think this might work for you, but I am guessing your Usercat class here:

我认为这可能对你有用,但我猜你的 Usercat 类在这里:

select c from Usercat as uc inner join uc.cat as c where uc.isFavourtie = true and uc.user = :user

回答by coding_idiot

Case Issue, Right query would be:

案例问题,正确的查询将是:

from Cat c inner join on Usercat uc where uc.isfavourtie = true and uc.user = :user

Note : C in Cat is capital, U in Usercat is capital where as c in Usercat is small and f in isfavourite is small.

注意:Cat 中的 C 是大写的,Usercat 中的 U 是大写的,因为 Usercat 中的 c 较小,而 isfavourite 中的 f 较小。