我希望@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
显式,但省略地址实体? (可能会在以后出现,但现阶段不知道。)