2017-06-21 12 views
0

是否有解決方案使用Java中的JPA聲明由兩個字段組成的主鍵?在Java中使用JPA組成的主鍵

例:

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private Long id; 

@Id 
private String identity; 

主鍵是(ID,身份)。

+0

看看這個頁面http://www.objectdb.com/java/jpa/entity/id在複合主鍵下 – kism3t

+0

@ kism3t我不忍受這個例子。或者,只需將'@ IdClass'添加到實體就足夠了? – youssef

回答

1

是的,您可以使用@IdClass註釋來指定一個類,它將被稱爲組合鍵。

例如:

@Table('myTable') 
@IdClass(ComposedKey.class) 
public class myEntity { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 

    @Id 
    private String identity; 

    private String otherFields; 

} 

public class ComposedKey implements Serializable { 
    private long id; 
    private String identity; 

    //Getter/Setter 

} 

然後,你的關鍵將是一個ComposedKey

+0

在'ComposedKey'類中,我只聲明瞭一個主鍵?而在我的實體中,我可以宣佈我的其他領域嗎? – youssef

+0

ComposedKey類僅用於處理組合主鍵。之後,你可以在你的實體中聲明你想要的東西。 –

0

是的,有幾種方法來完成這一點。在www中找到這個答案很容易。

看看這個:http://www.objectdb.com/java/jpa/entity/id#Composite_Primary_Key_

映入眼簾。

[更新]

我更喜歡採用嵌入式PK的:

@Embeddable 
public class ClassPK implements Serializable { 
    @Basic(optional = false) 
    @NotNull 
    @Size(min = 1, max = 145) 
    @Column(nullable = false, length = 145) 
    private String idOne; 
    @Basic(optional = false) 
    @NotNull 
    @Column(nullable = false) 
    private Integer idTwo; 
    @Basic(optional = false) 
    @NotNull 
    @Size(min = 1, max = 145) 
    @Column(nullable = false, length = 145) 
    private String idThree; 

然後在實體:

@Entity 
@Table(catalog = "", schema = "") 
public class Entity implements Serializable { 

    @EmbeddedId 
    protected ClassPK classPK ; 

    @Column(name = "date") 
    @Temporal(TemporalType.DATE) 
    private Date date; 
    @Column(name = "realTime", precision = 22) 
    private Double realTime; 
    @Size(max = 150) 
    @Column(name = "cnc", length = 150) 
    private String cnc; 

正如你可以在ID級別看,你可以有儘可能多的領域,你想(在我的情況下,我有一個複合PK的3個領域)。

並在實體中定義所有其他列。

+0

我看到了這個解決方案,但我不明白。如果進入我的課,我有一個由兩個字段組成的主鍵,我還有其他一些列,例如那個例子? '@Entity @IdClass(ProjectId.class) public class Project {@Id int departmentId; @Id long projectId; @column(name =「first_name」) }' – youssef

+0

您可以擁有任意數量的字段以及您的複合PK。 註解@IdClass只是指出您的實體在類ProjectId中聲明瞭PK。但是在你的實體中,你可以用通常的方式定義其他列。 但我更喜歡使用嵌入式id類。 –