Just a while ago I ran into a case where Hibernate would auto generate a wrong database schema when two entities were mapped on the same table. The good news: it’s my fault and not a bug. The better news: here’s an account of how to avoid it.
Let’s assume a mutable entity A mapped as:
<class name="A" table="TABLE_A"> <id name="id" column="id"> <generator class="native"/> </id> ... some properties ... </class>
This maps a class with a simple autoincremented ID to a mysql table.
Now I want an immutable version of a subset of the entity on the same table:
<class name="ImmutableA" table="TABLE_A" mutable="false"> <id name="id" column="id"> <generator class="assigned"/> </id> ... some properties ... </class>
Everything will run just fine until the day when you’ll require Hibernate to generate the database schema from scratch: all inserts on entity A will start failing with an exception complaining about no default value for id.
What happened? A quick look at the generated table schema via describe TABLE_A quickly reveals that the ID column was created without the autoincrement flag. Though I’ve mapped two entities to the same table, Hibernate will obviously figure out a single schema for that table – in this case it unfortunatelly omitted the autoincrement flag for the ID column.
The solution is rather trivial though: just switch the last generator from assigned to native.