如何为超类编写Hibernate Criteria查询,并检查某个子类?让我们假设我们有以下所有使用Hibernate-JPA映射的类:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Bar {
@Id
@Column(name = "id")
private Long id;
}
@Entity
@PrimaryKeyJoinColumn(name="bar_id")
public class Foo extends Bar {
}
@Entity
@PrimaryKeyJoinColumn(name="bar_id")
public class Goo extends Bar {
}
Run Code Online (Sandbox Code Playgroud)
在编写像这样的Criteria查询时,为了提高性能,我希望对子类使用左连接:
getSession()
.createCriteria(Bar.class)
.createAlias("Foo", "foo", CriteriaSpecification.LEFT_JOIN)
.add(Restrictions.isNotNull("foo.bar_id"))
.list();
Run Code Online (Sandbox Code Playgroud)
这失败了,因为关联路径"Foo"显然不起作用,但它会说明我想要的.或者有其他方式进行此类查询吗?我需要在超类上执行查询.如果我在SQL中完成它,它将如下所示:
select b.*
from bar b left join foo f on f.bar_id = b.id
where f.bar_id is not null;
Run Code Online (Sandbox Code Playgroud)
上面的SQL查询只是为了说明我的意思,我知道在特定情况下使用"普通"连接会更容易.