映射继承的字段

时间:2012-02-06 12:26:22

标签: java hibernate inheritance jpa

我在Weblogic 10.3.4上使用带有Hibernate 4的EJB 3。

当我尝试根据其父实体中不存在的属性选择实体时,我遇到了问题:

我的系统中有这样的东西:一个基本的抽象VehicleDefinition类和两个具体的子类 - CarDefinition和TruckDefinition。

另外,我有一个基本的抽象VehicleInstance和两个具体的子类 - CarInstance和TruckInstance。

在VehicleInstance中我有一个VehicleDefinition字段。

在TruckDefinition类中,我映射了VehicleDefinition或CarDefinition中不存在的字段(高度)。问题是,通过上面提到的映射,我不能使用HQL来通过TruckDefintion字段选择TruckInstance(即按卡车高度计算),因为TruckInstance只“知道”VehicleDefinition,而不是TruckDefinition。

映射是这样的:

@Entity
@Table(name = "VEHICLES" uniqueConstraints = {@UniqueConstraint(columnNames = {"TYPE_NAME"}) })
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "VEHICLE_TYPE", discriminatorType = DiscriminatorType.INTEGER)
public abstract class VehicleDefinition {...}

@Entity
@DiscriminatorValue("222")
public class CarDefenition extends VehicleDefinition {...}

@Entity
@DiscriminatorValue("555")
public class TruckDefenition extends VehicleDefinition{
    ...
    private Integer mHeight;

    @Column(name = "TRUCK_HIGHT")
    public Integer getHeight()
    {
        return mHeight;
    }
}

@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula("CASE WHEN 222 = (SELECT a.VEHICLE_TYPE FROM VEHICLES a WHERE a.id = VEHICLE_ID) THEN 222 ELSE 555 END")
@Table(name = "VEHICLE_INSTANCES" uniqueConstraints = {@UniqueConstraint(columnNames = {"VEHICLE_ID", "LPLATE"}) })
public abstract class VehicleInstance {
    ...

    private VehicleDefinition mDefinition
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "VEHICLE_ID" referencedColumnName = "ID", nullable = false)
    public VehicleDefenition getDefinition()
    {
        return mDefinition;
    }
}

@Entity
@DiscriminatorValue("222")
public class CarInstance extends VehicleInstance {...}

@Entity
@DiscriminatorValue("555")
public class TruckInstance extends VehicleInstance {...}

我尝试重构他的类,在VehicleInstance抽象中创建getDefinition,并使用TruckInstance和CarInstance实现,两者都返回它们的repectivetypes,但后来我无法弄清楚两个如何映射新方法。我应该在VehicleInstance上保留原始注释吗?它们都应该指向VEHICLE_ID吗?我试过的每一个组合似乎都失败了。

总而言之 - 我如何映射VehicleInstance,CarInstance和TruckInstance以便我可以根据其高度属性在HQL中选择TruckInstance?

提前致谢!

0 个答案:

没有答案