Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@OneToOne(optional=false) and @JoinColumn(nullable=false) used together

I've bumped into this example in JPA 2.0 FR Specification, 11.1.37. OneToOne Annotation, page 403:

@OneToOne(optional=false)
@JoinColumn(name="CUSTREC_ID", unique=true, nullable=false, updatable=false)
public CustomerRecord getCustomerRecord() { return customerRecord; }

Is there any reason that I should put @OneToOne(optional=false) and at that same time put @JoinColumn(... nullable=false)?

Aren't these two declarations the same? Isn't one of them redundant?
Are both of them used in DDL schema generation?

like image 388
Piotr Nowicki Avatar asked Nov 25 '11 23:11

Piotr Nowicki


People also ask

What does the annotation @basic optional false mean?

It means, if you try to persist an entity with a null field it will throw an exception if it is marked as optional=false (without contacting the database) and the entity will not be added to the JPA persistence context.

What is @manytoone optional false?

Description. This annotation will create a NOT NULL constraint on the column when it shouldn't. The JoinColumn configuration should override the default generated by "optional=false". This is relevant in single table inheritance situations.

Is @JoinColumn mandatory?

It is not necessary to have @JoinColumn annotation. You can always override it. If you won't provide it in your code then Hibernate will automatically generate one for you i.e. default name for your column. Could you please be more specific?

What is optional false in Hibernate?

1. optional=false is not working if you try to save the Personne without Adresse : "org.hibernate.PropertyValueException: not-null property references a null or transient value: " – Grégory. Nov 28, 2013 at 18:30. optional = false means that... the address is not optional.


1 Answers

Formally optional=false is a runtime instruction to the JPA implementation, and nullable=false is an instruction to the DDL generator. So they are not strictly redundant.

The difference can become significant when there is entity inheritance involved. If a particular mapping exists only on a subclass, and you have single table table per-hierarchy strategy, then the OneToOne mapping may be optional=false on the particular subclass that contains the mapping. However, the actual join column cannot be made not-null, since then other sub classes that share the table can't be inserted!

In practice different versions of different providers may or may not interpret either one at either time, caveat emptor.

like image 162
Affe Avatar answered Sep 22 '22 23:09

Affe