JPA / Hibernate:已创建表的注释

时间:2012-09-05 08:38:23

标签: java hibernate jpa

我有两个表(已经创建),比如人员和地址,下面是模式:

create table Person (
    `id` int(11) not null auto_increment,
    `name` varchar(255) default null,
    primary key(`id`)
)

create table Address (
    `id` int(11) not null,
    `city` varchar(255) default null,
    primary key (`id`),
    constraint foreign key (`id`) references `Person`(`id`)
)

现在,我应该在代码中使用哪些注释?

这两个类的骨架是:

class Person {
    @Id @GeneratedValue
    @Column(name="id")
    int id;
    String name;

    Address address;
}

class Address {
    int id;
}

我需要在类的地址字段和地址类的 id 字段中添加注释。< / p>

3 个答案:

答案 0 :(得分:1)

在Person.java中

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "id",nullable=false)
@ForeignKey(name = "fk_id")     
private Address address;   

和地址.java -

@OneToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "id", updatable = false, insertable = false, nullable=false)  
private Person id;    

@Column(name = "id", insertable = false, updatable = false, nullable=false)
private Integer id;

答案 1 :(得分:0)

 class Person {
   @Id @GeneratedValue
   @Column(name="id")
   int id;
   String name;

   @OneToOne
   @JoinColumn(name = "address_id", referencedColumnName = "id")
   Address address;
}

class Address {
    @id
    int id;
}

答案 2 :(得分:0)

我想你想使用@MapsId

@Entity
class Person {
   @Id 
   @GeneratedValue
   int id;

   String name;

   @OneToOne 
   @MapsId
   Address address;
}

@Entity
class Address {
    @Id
    int id;
}

查看@OneToOne文档中的示例2。