Skip to main content

@OneToOne(optional = false, ...) allows to save object with a null referenc

1 reply [Last post]
Anonymous

Hi.
I have a simple mapping: Category has a CategoryInfo reference. This is a one-to-one, not optional, and in one direction only. The database schema doesn't impose the not-null constraint on the foreign key.

<br />
@OneToOne(fetch = FetchType.EAGER, optional = false)<br />
@JoinColumn(name = "CATEGORY_INFO_ID")<br />
private CategoryInfo info;<br />

In the code, I create a new Category, and never assign a CategoryInfo to it, this is null, but the code runs fine, and the object is saved to the database. When I enable a not-null constraint, JDBC reports an error.

When I switch the provider from TopLink to Hibernate, and disable the not-null constraint again, running the same code results in an exception, which says that a not-null reference is null, which is what I expected.

So, there is a difference in behaviour between two providers. Could anyone tell me if this is allowed? Or maybe the optional attribute can be ignored by the provider?
I went here:
http://www.oracle.com/technology/products/ias/toplink/jpa/resources/topl...
and this description lacks the "optional" attribute at all, hence my question if this is optional or not.

Thank you.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
chris_delahunt
Offline
Joined: 2005-07-06

For the optional tag, The JPA 1 Spec states:
"(Optional) Whether the value of the field or property may be null. This is a hint and is disregarded for primitive types; it may be used in schema generation."

It is optional (most hints are), but TopLink/EclipseLink will use the tag for schema generation - relying on the database to do validation if it is required. If you used schema generation for your tables, you'd see they were created with the not-null constraint.

Best Regards,
Chris