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
A:
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.
Pascal Thivent
2010-03-26 13:54:16