2012-03-29 97 views

回答

19

這裏是Object DB一個很好的解釋。

指定ManyToOne或OneToOne關係屬性,該屬性爲EmbeddedId主鍵,EmbeddedId主鍵內的屬性或父實體的簡單主鍵提供映射。 value元素指定關係屬性對應的組合鍵內的屬性。如果實體的主鍵與關係引用的實體的主鍵具有相同的Java類型,則不指定value屬性。

// parent entity has simple primary key 

@Entity 
public class Employee { 
    @Id long empId; 
    String name; 
    ... 
} 

// dependent entity uses EmbeddedId for composite key 

@Embeddable 
public class DependentId { 
    String name; 
    long empid; // corresponds to primary key type of Employee 
} 

@Entity 
public class Dependent { 
    @EmbeddedId DependentId id; 
    ... 
    @MapsId("empid") // maps the empid attribute of embedded id 
    @ManyToOne Employee emp; 
} 

閱讀API Docs這裏。

1

我發現這說明還有用:@MapsId在Hibernate映射註釋與其他表的列列。

它也可用於共享2個表之間的相同的主鍵。

實施例:

@Entity 
@Table(name = "TRANSACTION_CANCEL") 
public class CancelledTransaction { 
    @Id 
    private Long id; // the value in this pk will be the same as the 
        // transaction line from transaction table to which 
        // this cancelled transaction is related 

    @OneToOne(fetch = FetchType.LAZY) 
    @JoinColumn(name = "ID_TRANSACTION", nullable = false) 
    @MapsId 
    private Transaction transaction; 
    .... 
} 

@Entity 
@Table(name = "TRANSACTION") 
@SequenceGenerator(name = "SQ_TRAN_ID", sequenceName = "SQ_TRAN_ID") 
public class Transaction { 
    @Id 
    @GeneratedValue(generator = "SQ_TRAN_ID", strategy = GenerationType.SEQUENCE) 
    @Column(name = "ID_TRANSACTION", nullable = false) 
    private Long id; 
    ... 
}