English 中文(简体)
使用特定的子类查找行的标准查询
原标题:Criteria query looking for rows using a specific subclass

我首先举个清洁的例子。

在我的系统里,我拿到了汽车类。汽车有多个领域,其中之一就是GearShift类的齿轮式轮椅。

public class Car {
    private GearShift gearShift;

    // Snip
}

Gearshift 是一个抽象的等级, Autome Shift 和 StickShift 继承了该等级。 它在 Hibernate 中被映射为每张表格的子类 。

现在,说我想让汽车自动换换齿。我更喜欢通过休眠标准来做到这一点, 所以我想象一个可以添加的“Type”限制, 如下面所示。

getSession().createCriteria(Car.class)
    .add(Restrictions.ofType(AutomaticShift.class)
    .list();

这有可能吗?

最佳回答

<强度>OLD:

这个怎么样?

getSession().createCriteria(AutomaticShift.class).list()

<强度 > EDIT:

这样做应该能解决问题;

getSession().createCriteria(Car.class).createAlias("gearShift", "gs").add(Restrictions.eq("gs.class", AutomaticShift.class)).list();
问题回答

也许听起来有点像管理费 但你可以分两步

  1. 获取自动齿轮的所有代碼 :

    List<Long> automaticGearIds = getSession().createCriteria(AutomaticShift.class)
                                            .setProjection(Projections.distinct(Property.forName("id")))
                                            .list();
    
  2. 把所有配有自动齿轮的汽车都弄来:

    return getSession().createCriteria(Car.class).add(Restrictions.in("gearShift.id", automaticGearIds)).list();
    




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签