Close

JPA - Making @OneToOne relationship mandatory by setting optional=false

@OneToOne annotation specifies an association to another entity that has one-to-one multiplicity. The Following example demonstrates that setting @OneToOne(optional=false) makes the association mandatory. For a mandatory association, the target entity cannot be persisted when it's associated reference is null.

The default value of 'optional' element is true.

Example Project

Dependencies and Technologies Used:

  • h2 1.4.193 (H2 Database Engine)
  • hibernate-core 5.2.8.Final (The core O/RM functionality as provided by Hibernate
    Implements javax.persistence:javax.persistence-api version 2.1)
  • JDK 1.8
  • Maven 3.3.9

jpa-one-to-one-optional-example Select All Download
  • jpa-one-to-one-optional-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • EntityA.java
          • resources
            • META-INF

    Running the main class (ExampleMain.java) will throw following exception.

    Output

    javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value : com.logicbig.example.EntityA.entityB
    at com.logicbig.example.ExampleMain.main (ExampleMain.java:20)
    Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value : com.logicbig.example.EntityA.entityB
    at com.logicbig.example.ExampleMain.main (ExampleMain.java:20)

    See also

    JPA - OneToOne relationship