2017-04-23 191 views
1

我有一個實體類一對一弱實體映射JPA

@Entity 
Class Search 
{ 
    @Id 
    private Long SearchID; 
    private String Type; 

} 

和其他實體類(SearchResult所這是一個弱實體依賴於搜索類別爲它的主鍵

@Entity 

Class SearchResults 

{ 
    @??? 
    private Long SearchID; 
} 

什麼我應該使用註釋將「搜索」實體類的「SearchID」指定爲我的主鍵在我的弱實體中「SearchResults」

+0

如果SearchResult所表有一個SearchID列,爲什麼不使用'@ Id'嗎?否則,你應該給我們關於這些表格的更多信息。 – ericbn

+0

但是我的「SearchResults」中的「searchID」取決於搜索類的「SearchID」。 –

回答

1

使用共享主鍵的JPA概念,可以將您的rel ationship如下:

主類:

@Entity 
public class Search { 
    @Id 
    private Long searchID; 
    private String type; 
} 

得到的標識符與單個屬性

@Entity 
public class SearchResults { 
    @Id 
    @OneToOne 
    @JoinColumn(name = "SEARCHID")  
    private Search search; 
} 

推導器標識符與共享映射

@Entity 
public class SearchResults { 
    @Id 
    private Long searchID; 

    @MapsId 
    @OneToOne 
    @JoinColumn(name = "SEARCHID")  
    private Search search; 
} 

完全一rticle here:http://vard-lokkur.blogspot.com.br/2014/05/onetoone-with-shared-primary-key.html

1

SearchResult不一定是一個實體。

雖然它可以被映射爲具有共享PK的Enity,如其他答案中所建議的那樣,但作爲弱實體,它不能獨立於其相關搜索存在,因此可以映射爲Embeddable。

https://en.wikibooks.org/wiki/Java_Persistence/Embeddables

@Entity 
public class Search 
{ 
    @Id 
    private Long SearchID; 

    private String Type; 

    @ElementCollection 
    @CollectionTable(....) 
    private Set<SearchResults> results; 
} 


@Embeddable 
public class SearchResults 
{ 
    //does not need an Id 

    //other fields 
}