Java 使用特定子类查找行的条件查询
我将从一个经过消毒的例子开始 在我的系统中,我拥有一流的汽车。Car有许多字段,其中包括gearShift类的gearShift实例Java 使用特定子类查找行的条件查询,java,hibernate,criteria,table-per-subclass,Java,Hibernate,Criteria,Table Per Subclass,我将从一个经过消毒的例子开始 在我的系统中,我拥有一流的汽车。Car有许多字段,其中包括gearShift类的gearShift实例 public class Car { private GearShift gearShift; // Snip } 换档是一个抽象类,AutomaticShift和StickShift从中继承。这在Hibernate中映射为每个子类的表 现在,假设我想要自动换档的汽车。我更喜欢通过Hibernate标准来实现这一点,所以我设想可以添加一个“of
public class Car {
private GearShift gearShift;
// Snip
}
换档是一个抽象类,AutomaticShift和StickShift从中继承。这在Hibernate中映射为每个子类的表
现在,假设我想要自动换档的汽车。我更喜欢通过Hibernate标准来实现这一点,所以我设想可以添加一个“of type”限制,如下所示
getSession().createCriteria(Car.class)
.add(Restrictions.ofType(AutomaticShift.class)
.list();
这有可能吗?旧的:
这个怎么样
getSession().createCriteria(AutomaticShift.class).list()
编辑:
这应该会奏效
getSession().createCriteria(Car.class).createAlias("gearShift", "gs").add(Restrictions.eq("gs.class", AutomaticShift.class)).list();
也许这听起来有点像开销,但您可以通过两个步骤完成:
List<Long> automaticGearIds = getSession().createCriteria(AutomaticShift.class)
.setProjection(Projections.distinct(Property.forName("id")))
.list();
你的地图绘制得怎么样?您是否使用鉴别器?为什么不选择使用HQL?CriteriaAPI不公开完整的Hibernate功能。这只会返回一个自动设备列表-1为this@RaulGogo当前位置这就是我认为他想要做的:你理解不同吗?他想要一份自动档汽车的清单。使用限制。在这种情况下是一种不好的做法。
return getSession().createCriteria(Car.class).add(Restrictions.in("gearShift.id", automaticGearIds)).list();