2015-09-22 217 views
6

我有以下表 enter image description here兩個外鍵作爲主鍵

我將如何實現這個使用Hibernate註解?

當前代碼是:(剝離爲了簡潔)

用戶

@Entity 
@Table(name = "user") 
public class User implements java.io.Serializable { 
    @Id 
    @GeneratedValue 
    public Long getId() { 
     return id; 
    } 
} 

SocialNetwork

@Entity 
@Table(name = "social_network") 
public class SocialNetwork implements java.io.Serializable { 
    @Id 
    @GeneratedValue 
    public int getId() { 
     return id; 
    } 
} 

SocialProfile

@Entity 
@Table(name = "social_profile") 
public class SocialProfile implements java.io.Serializable { 
    @Id 
    @ManyToOne 
    @JoinColumn(name="user_id") 
    public User getUser() { 
     return user; 
    } 

    @Id 
    @ManyToOne 
    @JoinColumn(name="social_network_id") 
    public SocialNetwork getSocialNetwork() { 
     return socialNetwork; 
    } 
} 

顯然我的代碼現在不能正常工作。任何人都可以對此有所瞭解嗎?

+1

您也可以考慮給你social_profile添加一個簡單的ID列,只是添加獨特的約束兩個FK在一起。這幾乎是相同的,但更容易處理,恕我直言 – stg

+0

@stg感謝您的提示,我在social_profile表中添加了一個'id',並且使得這些字段是唯一的而不是空的。這種方式更簡單。 – prettyvoid

回答

4

你需要一個嵌入式SocialProfileId這樣的:

@Embeddable 
public class SocialProfileId implements Serializable { 
    @Column(name = "user_id") 
    private long userId; 
    @Column(name = "social_network_id") 
    private long socialNetworkId; 
} 

然後,你SocialProfile實體將是這樣的:

@Entity 
@Table(name = "social_profile") 
public class SocialProfile implements java.io.Serializable { 

    @EmbeddedId 
    private SocialProfileId id; 

    @ManyToOne 
    @JoinColumn(name="user_id") 
    public User getUser() { 
     return user; 
    } 

    @ManyToOne 
    @JoinColumn(name="social_network_id") 
    public SocialNetwork getSocialNetwork() { 
     return socialNetwork; 
    } 
} 

編輯對不起,我有在我的答案上對字段和方法進行混合註釋......從來不這樣做! ;-)

+0

感謝您的信息。我會接受這個,但我決定使用像上面評論中提到的stg這樣的代理鍵,使事情變得更簡單。 – prettyvoid

+0

是的,有一個簡單的ID更簡單...我只是在這裏回答你的問題;-) – Pras

0

我對REST應用程序的問題很相似,但有點不同,我會在這裏發表。 我有2個數據表:歌曲 & 標籤與每個id(songid,tagid)。 然後,我有一張桌子將它們連接在一起Tagassignment其中只有SongTag的主鍵。所以我不想加入他們,我想用兩個外鍵保留表格。

來源我的解決方案:http://www.objectdb.com/java/jpa/entity/id


之前

@Entity 
@Table(name = "songs") 
data class Song(

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    val id: Int, 

    ... 
) 

標籤

@Entity 
@Table(name = "tags") 
data class Tag(

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    val id: Int, 

    ... 
) 

Tagassignment

@Entity 
@Table(name = "tagassignment") 
data class Tagassignment(

    val songid: Int, 

    val tagid: Int 

) 

後,我並沒有改變標籤

Tagassignment

@Entity 
@IdClass(value = TagassignmentKey::class) 
@Table(name = "tagassignment") 
data class Tagassignment(

    @Id 
    val songid: Int, 

    @Id 
    val tagid: Int 

) 

和我創建了一個Key類

TagassignmentKey

class TagassignmentKey(val songid: Int, val tagid: Int) : Serializable { 

    constructor() : this(0, 0) 

}