[英]How do I implement an “optional” relationship in Hibernate/JPA?
I'm using the Hibernate 3.6 implementation of JPA. 我正在使用JPA的Hibernate 3.6实现。 I have two tables in a logical parent-child relationship.
我在逻辑上的父子关系中有两个表。 Normally there would be one record in the "child" for each record in the "parent."
通常,“父级”中的每个记录在“子级”中都有一个记录。 The tables look like this:
这些表如下所示:
CREATE TABLE FOO (
FOO_ID INT IDENTITY,
BAR_ID INT DEFAULT 0 NOT NULL,
SOMEDATA CHAR(50) );
CREATE TABLE BAR (
BAR_ID INT IDENTITY,
OTHERDATA CHAR(50),
STILLOTHER CHAR(50)) ;
However, it has been decided that some "parent" records should not have "child" records and I should just put a 0
in the FOO.BAR_ID
column. 但是,已经决定某些“父”记录不应具有“子”记录,而我应该在
FOO.BAR_ID
列中仅输入0
。
How do I implement this in my entity classes? 如何在实体类中实现此功能? Right now the classes look like this:
现在,这些类如下所示:
public class Foo implements java.io.Serializable {
@Id
@GeneratedValue
@Column(name = "FOO_ID", unique = true, nullable = false)
private Long fooId;
@OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@JoinColumn(name = "BAR_ID", nullable = false)
private Bar bar;
}
public class Bar implements java.io.Serializable {
@Id
@GeneratedValue
@Column(name = "BAR_ID", unique = true, nullable = false)
private Long barId;
)
I can't seem find the right syntax to place a 0
in the FOO.BAR_ID
column and not try to create a record in the BAR
table. 我似乎找不到正确的语法在
FOO.BAR_ID
列中放置0
,并且不尝试在BAR
表中创建记录。 Can this even be done with Hibernate? 甚至可以用Hibernate完成吗?
@OneToOne(cascade = {CascadeType.MERGE, CascadeType.PERSIST})
@JoinColumn(name = "BAR_ID", nullable = false)
I believe you should try removing. 我相信您应该尝试删除。
nullable = false
You are telling hibernate that Foo's Bar can not be null. 您是在告诉休眠状态,Foo's Bar不能为null。 If Bar is optional then sometimes it must be null.
如果Bar是可选的,则有时它必须为null。 Since it can not be null and the CascadeType is Persist, Hibernate is saving the Bar that Foo must have when you save Foo.
由于它不能为null且CascadeType为Persist,因此Hibernate将保存Foo时Foo必须具有的Bar。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.