2010-03-26 67 views

回答

2

只需在表格中添加一列「擁有」與FK約束的關係即可。例如:

 
CREATE TABLE MYENTITYA (
     ID BIGINT NOT NULL, 
     MYENTITYB_ID BIGINT 
    ); 

CREATE TABLE MYENTITYB (
     ID BIGINT NOT NULL 
    ); 

ALTER TABLE MYENTITYA ADD CONSTRAINT SQL100326144838300 PRIMARY KEY (ID); 

ALTER TABLE MYENTITYB ADD CONSTRAINT SQL100326144838430 PRIMARY KEY (ID); 

ALTER TABLE MYENTITYA ADD CONSTRAINT FKB65AC952578E2EA3 FOREIGN KEY (MYENTITYB_ID) 
    REFERENCES MYENTITYB (ID); 

,將是這樣映射:

@Entity 
public class MyEntityA implements Serializable { 
    private Long id; 
    private MyEntityB myEntityB; 

    @Id 
    @GeneratedValue 
    public Long getId() { 
     return this.id; 
    } 

    @OneToOne(optional = true, cascade = CascadeType.ALL) 
    public MyEntityB getEntityB() { 
     return this.myEntityB; 
    } 

    //... 
} 

@Entity 
public class MyEntityB implements Serializable { 
    private Long id; 

    @Id 
    @GeneratedValue 
    public Long getId() { 
     return id; 
    } 

    //... 
} 

如果EntityAEntityB之間的關係是不可選的,然後添加一個NOT NULL約束。