【问题标题】:JPA/Hibernate: Annotations for already created tableJPA/Hibernate:已创建表的注释
【发布时间】:2012-09-05 08:38:23
【问题描述】:

我有两个表(已经创建),比如 Person 和 Address 具有以下架构:

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

我需要为 Person 类中的 address 字段和 Address 类的 id 字段添加注释。

【问题讨论】:

  • person id 和 address id 永远一样对吗?
  • 是的。实际上 Person 和 Address 是一对一的关系。

标签: java hibernate jpa


【解决方案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;

【讨论】:

  • 谢谢,但我无法在 Address 类中添加 Person 字段。
  • 这里的 person 代表 id。我已经修改了示例,您可以再次查看。在这里,我为一列创建了 2 个映射。一个会返回 id,另一个会返回 Person 对象。
【解决方案2】:

我想你想使用@MapsId

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

   String name;

   @OneToOne 
   @MapsId
   Address address;
}

@Entity
class Address {
    @Id
    int id;
}

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

【讨论】:

    【解决方案3】:
     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;
    }
    

    【讨论】:

    • 不确定这是否可行,因为架构中没有 address_id 列
    • 我们可以在 Address 类中为 id 字段设置列名“address_id”。行得通吗?
    • @JoinColumn(name = "address_id", referencedColumnName = "id") 表示 person 表中的 address_id 列将引用 address 表中的 id 列,但您需要在 person 表中创建 address_id 列。跨度>
    猜你喜欢
    • 2011-12-07
    • 1970-01-01
    • 2021-03-22
    • 2015-04-30
    • 2015-03-04
    • 1970-01-01
    • 2016-07-16
    • 2017-07-31
    • 1970-01-01
    相关资源
    最近更新 更多