We're using Hibernate 3.6.6 (yes, old, but for the moment, that's what we're stuck on). I've tested this issue on the latest of the 3.6 series, too. This is also a a Groovy 2.0.6 + Spring 3.2.1 app.
I'm have a class parent-child relationship, with a Distributor containing many DistributionCenters. My Distributor has a Set of DistributionCenters defined list this:
Code:
@OneToMany(mappedBy = 'distributor', cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
Set<DistributionCenter> centers = []
void addToCenters(DistributionCenter center) {
center.distributor = this
centers << center
}
and my DistributionCenter maintains the other side of the relationship this way:
Code:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "DISTRIBUTOR_ID", nullable = false)
Distributor distributor
My DistributionCenter also has some fields that are nullable=false.
The issue I'm having that I'd like to understand is ... when I have an existing Distributor that I've loaded from the database, and I've created a new DistributionCenter, I run into a "NULL not allowed for column..." exception if I don't fully set the state of the DistributionCenter before adding it to the Distributor. In other words, if I:
1) Load the Distributor
2) Create a DistributionCenter
3) Add DistributionCenter to Distributor (which ensures the parent-child relationship is fully populated)
4) Set the value of a nullable field to something other than null
5) Persist
I get the "NULL not allowed..." error.
If I just switch steps 3 & 4 ... then I'm good. and I don't see the error (fully setting state before adding to the parent).
I'd like to perform operations on the new instance after it's been added, but before I persist, as some state values are calculated in various methods.
Why would altering the order of the operations change the result? I've verified that the instance the PersistentSet is holding is the exact same instance I'm making mods to ... so I'm very puzzled.
Thanks!
Update: turning on hibernate logging, in the case that fails, we have an insert + update being issued; with the case that succeeds (inserting fully populated object), we see just an insert. This is similar to the discussion here http://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/example-parentchild.html but with the configuration I'm using, I wouldn't expect the null violation.