【问题标题】:JPA/hibernate inheritance and runtime type of an entity that subclasses an abstract super class/entity子类化抽象超类/实体的实体的 JPA/hibernate 继承和运行时类型
【发布时间】:2012-09-14 18:13:47
【问题描述】:

我需要一些关于 JPA/Hibernate 继承的说明。

假设我有一个抽象的Fruit 实体,它由两个AppleOrange 实体子类化。此外,我在数据库中有一个Orange 的实例。

我可以从数据库中检索此实例作为纯 Fruit 并将其转换为 Orange 吗?

【问题讨论】:

    标签: hibernate inheritance jpa entity runtime-type


    【解决方案1】:

    你可以这样做:

    Fruit fruit = dao.get(id, Fruit.class)
    if(fruit instanceof Orange)
    {
       (Orange) fruit
    }
    

    并且在运行时将是适当的类型。但是如果你写一个HQL,你可以检查它的运行时类型。如果您很好地完成了继承和映射,这通常是不需要的。

    select f from Fruit f where f.class = 'a.b.c.Fruit'
    

    【讨论】:

      【解决方案2】:

      select f from Fruit f where Treat(f as Orange).somePropetyInOrange=:value

      【讨论】:

        猜你喜欢
        • 2011-12-28
        • 2011-05-15
        • 2013-12-04
        • 2017-02-09
        • 1970-01-01
        • 2021-04-09
        • 2011-04-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多