Hibernate查询与别名 [英] Hibernate query with an alias
本文介绍了Hibernate查询与别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
session.createCriteria(Composed.class,main)
.createAlias( main.id.branch,b1)
.add(Restrictions.eq(b1.owner,user))
.list();
?相应的HQL工作正常
String hql =select main from Composed as main
+left join main。 id.branch as b1 where b1.owner =?;
session.createQuery(hql)
.setInteger(0,user.id()。intValue())
.list();
从Criteria中, Hibernate不创建连接并使用 where b1x1_.owner_id =?
,但在任何地方都没有 b1x1 _
,所以失败时显示could not prepare statement。
这些类很平凡
@Entity class Composed {
@ Id ComposedId id; //也试过@EmbeddedId
...不相关的东西
}
@Embeddable class ComposedId {
@ManyToOne(optional = false)分支分支;
...不相关的东西
}
@Entity类分支{
@Id整数ID;
@ManyToOne(可选= false)用户所有者;
...不相关的东西
}
@Entity类用户{
@Id整数ID;
...不相关的东西
}
更新
一>。对不起,如果没有SSCCE,这是很难重现。
解决方案
我没有尝试,但也许创建两个左连接的别名可以帮助您。我的意思是:
session.createCriteria(Composed.class,main)
.createAlias(main。 id,id1,JoinType.LEFT_OUTER_JOIN)
.createAlias(id1.branch,b1,JoinType.LEFT_OUTER_JOIN)
.add(Restrictions.eq(b1.owner,user ))
希望它有帮助!
What's wrong with
session.createCriteria(Composed.class, "main")
.createAlias("main.id.branch", "b1")
.add(Restrictions.eq("b1.owner", user))
.list();
? The corresponding HQL works fine
String hql = "select main from Composed as main"
+ "left join main.id.branch as b1 where b1.owner = ?";
session.createQuery(hql)
.setInteger(0, user.id().intValue())
.list();
From the Criteria, Hibernate creates no join and uses where b1x1_.owner_id=?
, but there's no b1x1_
anywhere, so it fails with "could not prepare statement".
The classes are rather trivial
@Entity class Composed {
@Id ComposedId id; // also tried @EmbeddedId
... irrelevant stuff
}
@Embeddable class ComposedId {
@ManyToOne(optional=false) Branch branch;
... irrelevant stuff
}
@Entity class Branch {
@Id Integer id;
@ManyToOne(optional=false) User owner;
... irrelevant stuff
}
@Entity class User {
@Id Integer id;
... irrelevant stuff
}
Update
I've finally created an SSCCE and filed an issue. Sorry for the confusing question, without the SSCCE, it's rather hard to reproduce.
解决方案
I didn't try but maybe creating two aliases with left join helps you. I mean this:
session.createCriteria(Composed.class, "main")
.createAlias("main.id", "id1", JoinType.LEFT_OUTER_JOIN)
.createAlias("id1.branch", "b1", JoinType.LEFT_OUTER_JOIN)
.add(Restrictions.eq("b1.owner", user))
Hope it helps!
这篇关于Hibernate查询与别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文