我的这部分模型如下:
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_documentCategoryId
和 entity_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";
但由于您也有引用的对象,您甚至可以使用 entity
和 category
作为参数编写一个更短的版本:
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/