There are two ways of doing this, the way that can get ugly performance-wise and the way that is painful and awkward.
The potentially ugly way is done on the ToOne end. Using Hibernate Annotations it would be:
@Entity
public class Foo
{
...
@ManyToOne
@JoinColumn( name = "DEVICEID" )
@NotFound( action = NotFoundAction.IGNORE )
private Device device;
...
}
Unfortunately, this forces a preemptive database hit (no lazy loading) because device can be null, and if Hibernate created a lazy Device then "device == null" would never be true.
The other way involves creating a custom UserType that intercepts requests for the ID 0 and returns null for them, and then assigning that to the primary key of Device with @Type. This forces the 0 ~ null interpretation on everyone with a foreign key into Device.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…