3

I have 2 tables, ENQUIRY and ELEMENT with a One-to-Many relationship such that an Enquiry has many Elements.

I would like to enforce Oracle's NOT NULL constraint on foreign key column ELEMENT.ENQUIRY_ID as this is best-practice. I have the following collection on the Enquiry object:

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "ENQUIRY_ID", referencedColumnName = "ID")
private Set<Element> elements = new HashSet<Element>();

When I enforce the NOT NULL constraint I receive the following stacktrace:

Caused by: java.sql.BatchUpdateException: ORA-01400: cannot insert NULL into ("ELEMENT"."ENQUIRY_ID")

So Hibernate is obviously persisting the collection of elements before the parent enquiry and then going back and doing an UPDATE on the foreign key field afterwards.

Is there a way to enforce the NOT NULL constraint on the collection foreign key field?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Andrew Eells
  • 735
  • 12
  • 30

1 Answers1

2

Have you tried nullable = false in @JoinColumn?

axtavt
  • 239,438
  • 41
  • 511
  • 482
  • Thanks axtavt, that worked, easy when you know how! I can't find a write-up anywhere - though may not be searching correctly - but have blogged about the scenario, your solution, and how Hibernate is interpreting the annotations at http://www.andrew-eells.com/2011/01/09/hibernate-foreign-key-collections-database-best-practice/ – Andrew Eells Jan 10 '11 at 18:07