2013-03-18 33 views
0

我正在尝试使用Oracle和JPA构建数据库模式。我是JPA新手,我一直直接使用sql。 我需要做的是创建两个表格:第一个包含当前VOIP呼叫,另一个包含这些呼叫的历史记录。这两张表是相同的。 在JPA我写了这个:JPA Cast Exception

@Entity 
@Table(name = "voip_currentCalls") 
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) 
public class VoipCurrentCall implements Serializable { 

    private static final long serialVersionUID = 1L; 
    protected CompositeID id; 
    protected Timestamp startTime; 
    protected Timestamp endTime; 
    protected String calledNumber; 
    protected String callingNumber;  
    protected Person contact; 
    protected CallSource source; 
    protected CallStatus status; 
    protected CallType type; 
    protected CallStage stage; 

@Entity 
@Table(name = "voip_historyCalls") 
public class VoipHistoryCall extends VoipCurrentCall implements Serializable { 
... 

正如你所看到的第二个表中没有其他领域,但它仅仅是和第一的延伸。 当我尝试将VoipCurrentCall强制转换为VoipHistoryCall时,我获得java.lang.ClassCastException:VoipCurrentCall不能转换为VoipHistoryCall。

你有什么建议吗?我可能错过了一些东西。 提前感谢大家!

+2

您不能将超类转换为子类。 – 2013-03-18 11:43:29

回答

2

好吧,如果你想投的对象是历史呼叫,然后投将最稳妥失败。 JPA实体仍然与普通Java对象绑定到相同的投射规则。案例分析:

Object obj = new Object(); 
String str = (String) obj; 

以上在运行时会产生一类转换异常,它不一样,如果一个字符串是一个对象,如果对象是不是字符串无所谓。就你的JPA设计而言,你实际上应该略有不同。 JPA提供了一些标准的方法来定义继承层次结构。在你的情况下,我会建议使用@MappedSuperclass。例如:

@MappedSuperclass 
public abstract class BaseVoipCurrentCall implements Serializable { 

    @Id 
    private CompositeID id; 

    private Timestamp startTime; 
    private Timestamp endTime; 
    private String calledNumber; 
    private String callingNumber;  
    private Person contact; 
    private CallSource source; 
    private CallStatus status; 
    private CallType type; 
    private CallStage stage; 

    // Constructors, getters/setters 
} 

@Entity 
@Table(name = "voip_currentCalls") 
public class VoipCurrentCall extends BaseVoipCurrentCall { 
    // Voip current call specific attributes and logic 
} 

@Entity 
@Table(name = "voip_historyCalls") 
public class VoipHistoryCall extends BaseVoipCurrentCall { 
    // Voip history call specific attributes and logic 
} 
+0

非常感谢您宝贵的建议!我的拳头错误是我忘记了Java继承规则的愚蠢行为,给JPA带来了所有的错误(对我而言,这仍然是一个晦涩难懂的技术),但是当你证明我时,还有一个设计问题。 – 2013-03-18 13:31:46

4

这是Java设计的方式;只有反过来才能将超类转换为子类。它与JPA没有任何关系。

+0

我太专注于JPA,netbeans并没有给我证明我的愚蠢,所以我突然想到这是JPA问题!对不起!! – 2013-03-18 13:26:33