使用JPA一对一关系 [英] one-to-one relationship using JPA

查看:302
本文介绍了使用JPA一对一关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用JPA创建了两个表。我需要给这些表之间1-1关系。谁能告诉我如何在这些表之间建立关系。

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.

推荐答案

只需在表中拥有该关系的列有FK约束。例如:

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);

将被这样映射:

@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;
    }

    //...
}

如果 EntityA EntityB 之间的关系不是可选的,则添加 NOT NULL 约束。

If the relation between EntityA and EntityB is not optional, then add a NOT NULL constraint.

这篇关于使用JPA一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆