问题
I have created two table using JPA. i need to give 1-1 relationship between these tables. Can any one tell me how to give relationship between these tables.
回答1:
Simply add a column in the table "owning" the relation with a FK constraint. For example:
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);
That would be mapped like this:
@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;
}
//...
}
If the relation between EntityA
and EntityB
is not optional, then add a NOT NULL
constraint.
来源:https://stackoverflow.com/questions/2523528/one-to-one-relationship-using-jpa