没有鉴别器或层次结构的OneToOne映射

时间:2014-11-04 21:42:39

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

我在遗留数据库中有两个表,我正在尝试在其上创建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;
}

1 个答案:

答案 0 :(得分:0)

见下文:

@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