2013-03-18 34 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