控制 Hibernate 生成的子选择

发布于 2024-08-18 18:25:51 字数 650 浏览 6 评论 0原文

考虑以下三个 Hibernate 实体:

public class Car {

  @OneToMany(fetch = FetchType.LAZY)
  @Fetch(FetchMode.SUBSELECT)
  private List<Wheel> wheels;

}

public class Wheel {

  @OneToOne(fetch = FetchType.LAZY)
  private Hubcap hubcap;

}

public class Hubcap {

}

考虑以下标准:

Criteria criteria = getSession().createCriteria(Car.class);
List<Car> cars = criteria.list();

for (Car car : cars) {
  Hibernate.initialize(car.getWheels());
}

是否有任何方法可以控制将生成的子选择查询?具体来说,我想加入子选择,以便在获取车轮时也获取轮毂盖。这当然可以通过将 FetchType 更改为 EAGER 来完成,但我需要一些更特别的东西 - 在逐个查询的基础上。

由于代码当前,我需要生成另一个选择来获取轮毂盖。

Consider the following three Hibernate entities:

public class Car {

  @OneToMany(fetch = FetchType.LAZY)
  @Fetch(FetchMode.SUBSELECT)
  private List<Wheel> wheels;

}

public class Wheel {

  @OneToOne(fetch = FetchType.LAZY)
  private Hubcap hubcap;

}

public class Hubcap {

}

Consider the following Criteria:

Criteria criteria = getSession().createCriteria(Car.class);
List<Car> cars = criteria.list();

for (Car car : cars) {
  Hibernate.initialize(car.getWheels());
}

Is there any way to control the subselect query that will be generated? Specifically I'd like to join in the subselect so that the hubcaps are also fetched when the wheels are fetched. This can of course be accomplished by changing the FetchType to EAGER, but I need something more ad hoc - on a query by query basis.

As the code is currently I'd need to generate another select to fetch the Hubcaps.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

錯遇了你 2024-08-25 18:25:51

是的,你可以使用标准来做到这一点,但我不记得它是如何完成的,只需寻找标准中的联接,但是我建议使用 HQL 而不是 Criteria 更具可读性:

select c 
from Car c join fetch c.wheels
where ...

Yes you can do it using criteria but I don't remember how its done, just look for joins in criteria, however I would suggest using HQL rather Criteria is far more readable:

select c 
from Car c join fetch c.wheels
where ...
递刀给你 2024-08-25 18:25:51

您可以使用 setFetchMode 方法更改条件查询中的获取类型。

http://docs.jboss.org/hibernate/ core/3.3/reference/en/html/querycriteria.html

You can change the fetch type in a criteria query with the setFetchMode method.

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/querycriteria.html

眼前雾蒙蒙 2024-08-25 18:25:51

经过大量研究后发现,在现阶段这是不可能的,至少在不扩展 Hibernate 的情况下是不可能的。

After lots of research it appears that this is impossible at this stage, at least without extending Hibernate.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文