【问题标题】:Hibernate/HQL to achieve SQL WHERE ... IN (SELECT...) queryHibernate/HQL实现SQL WHERE...IN(SELECT...)查询
【发布时间】:2012-12-19 22:53:18
【问题描述】:

使用 Hibernate 实现与以下涉及子查询的 SQL 查询等效的最佳方法是什么:

SELECT cat.description, cat.code FROM
  THING_CATEGORY cat
WHERE cat.code IN (
  SELECT thing.CATEGORY_CODE FROM THING thing
  WHERE thing.COUNTRY_CODE IN ('AU', 'US', 'UK')
)

最好的方法可能是将它直接传递给数据库,以便在我的数据库的 SQL (PL/SQL) 风格中本地完成,但我实际上无法弄清楚它是如何在 Hibernate 中完成的@ 987654322@ object 所以我特别想知道。

请注意:THING 表绝对庞大且包含许多列,因此我不想从数据库中拉下所有THING 实体来实现此逻辑,因为它不会高效。限制THING_CATEGORY 结果的逻辑必须在可以优化的数据库内完成。事实上,当我使用原始 PL/SQL 进行查询时,几乎需要一秒钟才能得到结果。

给出实体的概念(注意THING_CATEGORY 没有引用回THING):

@Entity @Table(name = "THING")
public class Thing
{
  private String categoryCode;
  @Column(name = "CATEGORY_CODE", nullable = false, length = 3)
  public String getCategoryCode() { return this.categoryCode; }

  private String countryCode;
  @Column(name = "COUNTRY_CODE", nullable = false, length = 2)
  public String getCountryCode() { return this.countryCode; }

  ...
}

@Entity @Table(name = "THING_CATEGORY")
public class ThingCategory
{
  private String code;
  @Id @Column(name = "CODE", unique = true, nullable = false, length = 3)
  public String getCode() { return this.code; }

  ...
}

【问题讨论】:

    标签: hibernate subquery hibernate-criteria where-in


    【解决方案1】:

    当我即将发布问题时,我意识到答案是使用 Hibernate DetachedCriteria 来包含 THING 限制子查询。然后将其添加到THING_CATEGORY 主查询的条件中。

    Hibernate 代码如下所示:

    public List<ThingCategory> getRestrictedByCountrySet(List<String> countryCodes)
    {
      Criterion thingCriterion = Restrictions.in("countryCode", countryCodes);
      DetachedCriteria thingSubQuery = DetachedCriteria.forClass(Thing.class)
        .add(thingCriterion)
        .setProjection(Projections.property("categoryCode");
    
      Criteria thingCategoryCriteria = getHbSession().createCriteria(ThingCategory.class)
        .add(Property.forName("code").in(thingSubQuery));
    
      return thingCategoryCriteria.list();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-04-18
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2023-02-02
      相关资源
      最近更新 更多