【问题标题】:OneToOne mapping without discriminator or hierarchy没有鉴别器或层次结构的 OneToOne 映射
【发布时间】:2014-11-04 21:42:38
【问题描述】:

我在旧数据库中有两个表,我正在尝试在其上创建 Java 模型(使用 JPA 2.0 和 Hibernate 4)

create table master (
  master_id                      number(38) not null, --this is the primary key 
  ...
)

create table child (
  master_id                      number(38) not null, --the primary key and also a foreign key to master.id
  ...
)

我已经创建了实体,但是对于在每个类上使用哪些注释感到非常困惑。 @JoinColumn? @PrimaryKeyJoinColumn? @Id?

我知道Master 将管理Java 层中的持久性。也就是说,持久化和更新将从Master 级联。这一定是一个基本问题,但我是 JPA 的新手。

@Entity
class Master {

  @Id
  @Column (name="master_id")

  @OneToOne
  private Child child;

}

@Entity
class Child {

  @OneToOne
  private Master master;
}

【问题讨论】:

    标签: hibernate jpa jpa-2.0 one-to-one


    【解决方案1】:

    见下文:

    @Entity
    class Master {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        @OneToOne(mappedBy = "master")
        private Child child;
    }
    
    @Entity
    class Child {
    
        @Id
        @OneToOne
        @JoinColumn(name = "master_id")
        private Master master;
    }
    

    更多信息:

    http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Primary_Keys_through_OneToOne_and_ManyToOne_Relationships

    【讨论】:

    • 抱歉,我不清楚,child.master_id 也是PK,而不仅仅是外键。我将编辑主要问题。
    • 它最终与@MapsId 一起工作,正如vard-lokkur.blogspot.ca/2014/05/…中所建议的那样
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    • 1970-01-01
    相关资源
    最近更新 更多