Java HQL和连接-更快的方法?

Java HQL和连接-更快的方法?,java,performance,hibernate,join,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}

我的模型的这一部分如下所示:

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;
}
但是找不到该属性

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

是否有方法引用联接字段而不是对象引用?

要避免联接,请使用
.id

String q = "from Document d where d.documentCategory.id = :c and d.entity.id = :e";
但由于您也有引用的对象,您甚至可以使用
实体
类别
作为参数编写较短的版本:

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都能够确定它实际上不需要联接。

父id上有索引吗?是的,两个id上都有索引。记录Hibernate生成的SQL并检查查询,运行探查器查看热点是什么。您是否尝试使用identifier属性
.id
来避免联接
String q=“来自文档d,其中d.documentCategory.id=:c和d.entity.id=:e”谢谢wero!这很有效。我不知道,身份证是一种特殊的财产。我以为它会抱怨找不到房产,但不,这似乎很有效,消除了连接。再次感谢!根据您所说的,我原来的HQL查询实际上并没有执行连接!我现在觉得自己很笨。Hibernate HQL似乎比我聪明!
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);