Hi, there everyone. I'm using Hibernate 3.0 to persist my objects to a MySQL 4.0 database. I'm hoping someone out there can tell me what part of the manual I've missed, because I'm sure my problem is covered somewhere.
In the simplified scheme of things, I have two classes. A parent, Story, which contains a name property and a set of child Character objects, and Character, which contains a name property and a parent property pointing back to a Story object. My mapping document looks like this:
Code:
<class name="net.infinities.Character" table="characters">
<id name="id" type="long">
<column name="id" sql-type="int(16)" not-null="true"/>
<generator class="org.hibernate.id.IdentityGenerator"/>
</id>
<property name="name" type="string" unique-key="char_unique"/>
<many-to-one name="stories">
<column name="story_id" sql-type="int(16)" unique-key="char_unique">
</many-to-one>
</class>
<class name="net.infinities.Story" table="stories">
<id name="id" type="long">
<column name="id" sql-type="int(16)" not-null="true"/>
<generator class="org.hibernate.id.IdentityGenerator"/>
</id>
<property name="name" type="string" unique="true"/>
<set name="characters" inverse="true" cascade="all">
<key column="story_id"/>
<one-to-many class="net.infinities.Character"/>
</set>
</class>
Since uniqueness of characters is based on their name and the story they're in (e.g., "Scott" appears in both "The Window" and "Killing Time"), my problem comes from the fact that a Character can exist without a related story. MySQL's unique constraints ignore NULL values in database columns, so when Hibernate maps two new Characters with the same name and no Story, I end up with the following in my database:
Code:
id | name | story_id
------------------------
1 | Scott | NULL
2 | Scott | NULL
This should have caused a unique constraint violation, which I can trap and deal with, but MySQL isn't being very helpful with it's treatment of NULL in a unique contraint.
What I'm looking for is either a way to specify a null-value mapping of the Character class' story_id value (so it could be a real value that simply doesn't relate to a story), or advice on the pros and cons of having my persistence logic check for an existing character before attemping an insert, rather than relying on database-level constraints.
-- Alec