Hibernate 条件: 在没有映射关联的情况下连接表

我想使用 Hibernate 的标准 api 来制定一个连接两个实体的特定查询。假设我有两个实体,Pet 和 Owner,其中一个所有者拥有许多宠物,但关键是这种关联没有映射到 Java 注释或 xml 中。

使用 hql,我可以通过在查询中指定连接来选择拥有名为“ fido”的宠物的主人(而不是将一组宠物添加到主人类中)。

使用冬眠标准也可以做到这一点吗? 如果可以,怎么做?

谢谢, J

96361 次浏览

My understanding is that if you do this using HQL, you are creating a Cartesian join with a filter, rather than an inner join. Criteria queries do not support doing this.

There's a SQLCriterion, which you can give arbitrary SQL, and add to your Criteria. In the SQL string, the token {alias} "will be replaced by the alias of the root entity."

In NHibernate you can use subqueries which are defined as DetachedCriteria. Not sure if it works the same in Java, most probably it is the same:

DetachedCriteria pets = DetachedCriteria.For<Pet>("pet")
.SetProjection(Projections.Property("pet.ownername"))
.Add(/* some filters */ );


session.CreateCriteria(typeof(Owner))
.Add(Subqueries.PropertyIn("name", pets);

Assumed that it is joined using the name of the owner.

This is indeed possible with criteria:

DetachedCriteria ownerCriteria = DetachedCriteria.forClass(Owner.class);
ownerCriteria.setProjection(Property.forName("id"));
ownerCriteria.add(Restrictions.eq("ownername", "bob"));


Criteria criteria = getSession().createCriteria(Pet.class);
criteria.add(Property.forName("ownerId").in(ownerCriteria));

Update: This actually performs a sub-query instead of a join but it allows you to use Criteria on two entities that do not have a hibernate relationship defined.

Criterion ownerCriterion = Restrictions.sqlRestriction(SELECT ownerId FROM   Owner WHERE ownerName ='bob');
Criteria criteria = getSession().createCriteria(Pet.class);
criteria.createCriteria("ownerId").add(ownerCriterion);