2012-01-07 104 views
2

我正面臨着一種典型的問題。想象一下物體之間典型的1-N關係。準確地說,用戶(U)和房間(R):[U] * - 1 [R]。JPA與ManyToOne映射的超類

問題在於,房間應該是抽象基類,例如BlueRoom,RedRoom的實現。如何正確設置用戶實體內的關係?

public interface Room { ... } 
@MappedSuperclass 
public abstract class RoomSuperclass implements Room { ... } 
@Entity 
public class BlueRoom extends RoomSuperclass { ... } 
@Entity 
public class RedRoom extends RoomSuperclass { ... } 


@Entity 
public class User { 

    @ManyToOne(targetEntity = ???) // I don't know if it will be BlueRoom or RedRoom 
    private Room room; // ManyToOne cannot be applied on mapped superclass 
} 

我知道這可能會通過RoomSuperclass而不是使用@MappedSuperclass被@Entity可能解決,但我不知道這是否是很好的解決方案,如果有任何更好的。

+1

是的,這是解決方案。如果你有某種關聯,那麼這個東西必須是一個實體。 – 2012-01-07 20:11:30

+0

感謝您的回覆JB,我會等待一天,如果其他人回覆,然後關閉問題 – d1x 2012-01-07 20:24:19

回答

1

根據該帖子下的評論。將超類聲明爲@Entity是解決方案。

+0

您能解釋爲什麼有@MappedSuperclass? – salocinx 2015-09-18 15:38:31

+1

我想知道完全相同的該死的東西。我試圖使用這個註釋讓我的頭撞在牆上半天,因爲我不想將我的抽象實體映射到表中!這是抽象的!但不,如果我想使用繼承,我必須指定一個映射的實體,那麼這個註釋是什麼? – Alex 2017-02-16 10:12:30