Hibernate/JPA查询和类别存在问题

Hibernate/JPA查询和类别存在问题,hibernate,jpa,hql,categories,Hibernate,Jpa,Hql,Categories,我有一个Hibernate/JPA数据模型,可以将对象(MyObj)放入各种类别(MyCategory)。每个类别可能有0个或多个子类别,而没有为其指定分类(MyClassification)的类别。数据模型如下所示: public class MyObj { … protected MyCategory category = null; … } public class MyCategory { … protected MyClassific

我有一个Hibernate/JPA数据模型,可以将对象(MyObj)放入各种类别(MyCategory)。每个类别可能有0个或多个子类别,而没有为其指定分类(MyClassification)的类别。数据模型如下所示:

public class MyObj {

    …

    protected MyCategory category = null;

    …
}

public class MyCategory {

    …

    protected MyClassification classification=null;

    protected List<MyCategory> childCategories=null;

    protected MyCategory parentCategory=null;

    …

}

public class MyClassification {

    …

}
MyObj.findByClass = "SELECT DISTINCT o FROM MyObj o WHERE (o.category.classification = :classification OR o.category.parentCategory.classification = :classification)"

MyObj.findByCategory = "SELECT DISTINCT o FROM MyObj o WHERE (o.category = :category OR o.category.parentCategory = :category)"
from(QCategory.category)
.where(QCategory.category.classification.eq(classification).or(QCategory.category.left().parentCategory().left().classification.eq(classification))
.listDisticnt(QCategory.category)
有人能告诉我这些查询的逻辑错误在哪里吗?有没有更好的方法来完成我的目标?

我认为您在第一个查询中缺少了一个“分类”,在OR之后:

MyObj.findByClass = "SELECT DISTINCT o FROM MyObj o WHERE (o.category.classification = :classification OR o.category.parentCategory.classification = :classification)"

另一方面,我的感觉是遍历对象图比发出HQL查询更简单

查询的问题是
o.category.parentCategory
的编写方式类似于cat.id=o.parent\u category上的
内部连接类别cat,如果
parentCategory
NULL
,则不会得到任何结果

因此,点导航意味着内部联接,这会导致
语句出现问题。必须使用显式
左联接
联合
查询

另一方面,QueryDSL允许编写如下语句:

public class MyObj {

    …

    protected MyCategory category = null;

    …
}

public class MyCategory {

    …

    protected MyClassification classification=null;

    protected List<MyCategory> childCategories=null;

    protected MyCategory parentCategory=null;

    …

}

public class MyClassification {

    …

}
MyObj.findByClass = "SELECT DISTINCT o FROM MyObj o WHERE (o.category.classification = :classification OR o.category.parentCategory.classification = :classification)"

MyObj.findByCategory = "SELECT DISTINCT o FROM MyObj o WHERE (o.category = :category OR o.category.parentCategory = :category)"
from(QCategory.category)
.where(QCategory.category.classification.eq(classification).or(QCategory.category.left().parentCategory().left().classification.eq(classification))
.listDisticnt(QCategory.category)

从MyObj o中选择DISTINCT o,其中(o.category.classification=:classification或o.category.parentCategory.classification=:classification)

更正了查询中缺少的字段。is right、SQL(或HQL)无法以简单的方式在树中搜索…您可以使用所需的分类搜索所有类别,并使用第二个HQL使用找到的任何类别搜索所有Obj。