one-to-one relationship using JPA

别来无恙 提交于 2019-12-11 15:45:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!