ID trouble with multiple Hibernate entities on the same table

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"/>
... some properties ...

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"/>
... some properties ...

 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. 

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.