Hibernate query with an alias

雨燕双飞 提交于 2019-12-07 05:04:20

问题


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.


回答1:


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!




回答2:


You need a sub criteria for the join instead of an alias since Branch is a mapped Entity.

session.createCriteria(Composed.class, "main")
    .createCriteria("main.id.branch", "b1")
    .add(Restrictions.eq("b1.owner", user))
    .list();


来源:https://stackoverflow.com/questions/34104961/hibernate-query-with-an-alias

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!