简体   繁体   English

JPA / Hibernate:已创建表的批注

[英]JPA/Hibernate: Annotations for already created table

I have two tables (already created), say Person and Address with following schemas: 我有两个表(已创建),说具有以下模式的“人”和“地址”:

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

Now, which annotations should I use in the code? 现在,我应该在代码中使用哪些注释?

The skeletons of both the classes are: 这两个类的框架是:

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

    Address address;
}

class Address {
    int id;
}

I need to add annotations for address field in Person class and id field of Address class. 我需要添加地址栏标注在Address类的Person类和id字段。

in Person.java 在Person.java中

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

and in Address .java - 并在地址.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;
 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;
}

I think you want to use @MapsId . 我认为您想使用@MapsId

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

   String name;

   @OneToOne 
   @MapsId
   Address address;
}

@Entity
class Address {
    @Id
    int id;
}

Check out example 2 in the @OneToOne documentation. 请查看@OneToOne文档中的示例2。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM