在Hibernate Inheritance中更改子类型 [英] Change subtype in Hibernate Inheritance

查看:95
本文介绍了在Hibernate Inheritance中更改子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  @Entity 
@Inheritance

我有三个我想在Play!Framework中使用Hibernate进行建模的类: (strategy = InheritanceType.JOINED)
public class SupplyArea extends Model {
public int scadaId;
公共字符串符号;
}

@Entity
public class HighVoltageSubstation extends SupplyArea {
public int hvAttribute;
}

@Entity
public class MediumVoltageSubstation extends SupplyArea {
public int mvAttribute;
}

感谢Play!我已经定义了主键标识符ID。

它在大多数情况下工作正常:我有三个数据库表,HVSubstation和MVSubstation标识符被创建为外键SupplyArea等。



但我不'拥有'这些对象,我需要从其他来源导入它们。然后,如果另一个应用程序发生了变化,我需要更新我的。问题在于对象何时改变其类型:它不再是HVSubstation,而是现在的MVSubstation。所有其他参数(即。scadaId,符号)保持不变。它是相同的对象,但有另一种类型。



有什么方法可以在不丢失主键标识符的情况下在子类型之间切换?我试过这样的东西:

  SupplyArea oldArea = SupplyArea.getByScadaId(scadaId); //返回HVSubstation 
SupplyArea newArea = new MVSubstation();
newArea.id = oldArea.id;
newArea.scadaId = scadaId;
newArea.symbol = symbol;
oldArea.delete();
newArea.save();

显然,它不起作用。

解决方案

如果变电站可以从高电压变为中电压(或后退),我不会将它们建模为单独的子类型。相反,我只是使用一个带属性的SubStation类型来确定它是高电压还是中电压。在Hibernate中,它将映射到带有鉴别器属性的单个表。


I have three classes I want to model using Hibernate in Play!Framework:

@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class SupplyArea extends Model {
    public int scadaId;
    public String symbol;
}

@Entity
public class HighVoltageSubstation extends SupplyArea {
    public int hvAttribute;
}

@Entity
public class MediumVoltageSubstation extends SupplyArea {
    public int mvAttribute;
}

Thanks to Play! I already have defined primary key identifier id.

It works fine most of the time: I've got three database tables, HVSubstation and MVSubstation identifiers are created as foreign keys to SupplyArea and so on.

But I don't 'own' the objects, I need to import them from another source. Then, if something changes in another application, I need to update mine. The problem is when the object changes its type: it is no more a HVSubstation, it is now a MVSubstation. All other parameters (ie. scadaId, symbol) remain the same. It is the same object, but has another type.

Is there any way to switch between subtypes without losing my primary key identifier? I tried something like this:

SupplyArea oldArea = SupplyArea.getByScadaId(scadaId); // returns HVSubstation
SupplyArea newArea = new MVSubstation();
newArea.id = oldArea.id;
newArea.scadaId = scadaId;
newArea.symbol = symbol;
oldArea.delete();
newArea.save();

Obviously, it does not work.

解决方案

If the substations can change from high to medium voltage (or back), I would not model these as separate subtypes. Instead, I would just use a single SubStation type with a property to determine whether it's high or medium voltage. In Hibernate, that would map to a single table with a discriminator property.

这篇关于在Hibernate Inheritance中更改子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆