使用可选的外键保留@ManyToOne?

时间:2016-01-20 15:23:54

标签: java hibernate postgresql

我希望@Entity持有@ManyToOne @JoinColumn引用,该引用应该是可选的。

但是当我尝试保留以下Person类,其中设置了locationId,但未设置address重新引用时,我收到了PSQLException: voilates foreign key constraints例外。< / p>

我的课程如下:

@Entity
public class Person {
    @Id
    private Long id;
    private String name;
    private int locationId;

    @ManyToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.DETACH})
    @JoinColumn(name = "location_id", foreignKey = @ForeignKey(name="fk_address"), nullable = true)
    private AddressEntity address;
}

@Entity
public class AddressEnity {
    @Id
    private int locationId;

    //street, zip, town etc

    @OneToMany(mappedBy = "address")
    private Set<Person> persons;
}

hibernate生成的架构:

CREATE TABLE person(
  id bigint NOT NULL,
  name character varying(255),
  location_id interger NOT NULL,
  CONSTRAINT fk_address FOREIGN KEY (location_id)
    REFERENCES addresses (location_id) MATCH SIMPLE
    ON UPDATE NO ACTION ON DELETE NO ACTION
);

CREATE TABLE address(
  location_id integer NOT NULL,
  //street, zip, town, etc
   CONSTRAINT location_id_pk PRIMARY KEY (location_id)
);

问题:是不是可以保存locationId显式,但省略地址实体? (可能会在以后出现,但现阶段不知道。)

0 个答案:

没有答案