java - HQL 和连接——更快的方法?

标签 java performance hibernate join hql

我的这部分模型如下:

IQCEntity has many Documents
DocumentCategory has many Documents

我正在为我的 ORM 使用 Hibernate。

现在,请考虑以下方法:

/**
 * Get all documents in the supplied IQCEntity which are in the
 * specified DocumentCategory.
 * @param entity the {@link IQCEntity} which holds the Documents
 * @param category the {@link DocumentCategory} which the Documents belong to
 * @return Collection<{@link Document}>
 */
@SuppressWarnings("unchecked")
public Collection<Document> getDocuments(IQCEntity entity, DocumentCategory category) { 
    String q = "from Document d where d.documentCategory.documentCategoryId = :c and d.entity.entityId = :e";
    Query query = session.createQuery(q);
    query.setParameter("c", category.getDocumentCategoryId());
    query.setParameter("e", entity.getEntityId());
    List<Document> documents = (List<Document>)query.list();
    Collections.sort(documents);
    return documents;
}

此方法有效,并返回正确的结果,但它似乎很慢。

如果我查看数据库中的表结构,Document 表有父 ID(当然有 - 否则它怎么可能加入!)、documentCategory_documentCategoryIdentity_entityId.

我们都知道,在 SQL 中,根本不需要任何连接就可以得到正确的结果。如何在 HQL 中完成同样的操作?

我试过这个:(注意 _ 而不是 .)

String q = "from Document d where d.documentCategory_documentCategoryId = :c and d.entity_entityId = :e";

但是找不到属性。

org.hibernate.QueryException: could not resolve property: documentCategory_documentCategoryId of: com.foo.bar.entities.Document

有没有什么方法可以引用连接字段而不是对象引用?

最佳答案

要避免连接,请使用 identifier property .id:

String q = "from Document d where d.documentCategory.id = :c and d.entity.id = :e";

但由于您也有引用的对象,您甚至可以使用 entitycategory 作为参数编写一个更短的版本:

String q = "from Document d where d.documentCategory = :c and d.entity = :e";
Query query = session.createQuery(q);
query.setParameter("c", category);
query.setParameter("e", entity);

在这两个版本中,Hibernate 都能够弄清楚它实际上不需要加入。

关于java - HQL 和连接——更快的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32005856/

相关文章:

database - 如果 postgres 的性能低下,我应该选择哪个数据库

c# - ASP.NET Web API 性能问题

mysql - ManyToMany @Embeddable MySQLIntegrityConstraintViolationException : Cannot add or update a child row: a foreign key constraint fails

java - Hibernate 继承 - 获取父类(super class)实例并转换为子类

java - 映射 google 自定义搜索 api URL 中的文本框值

Java有一个39G的核心转储

java - 在 RHS 处引用 Spring XML 中的属性的属性?

java - 如何回滚除异常之外的所有内容以存储在表中

javascript - 我怎样才能 "Reduce JavaScript execution time"的外部脚本?

java - 日期的 hibernate 条件