Friday, February 4, 2011

Hibernate mapping a composite key with null values

Hi,

With Hibernate, can you create a composite ID where one of the columns you are mapping to the ID can have null values?

This is to deal with a legacy table that has a unique key which can have null values but no primary key.

I realise that I could just add a new primary key column to the table, but I'm wondering if there's any way to avoid doing this.

  • Why would you want to do that? Your composite ID should map the primary key of your table, and it doesn't sound wise to put null values in a key, does it?

    EDIT: Hibernate does not allow to do so; you might put the property outside the key and tweak the DAO a little to take the field into account wherever necessary

    Brett Ryan : Mapping to legacy tables is one reason why this might be required. I have a case where this is also required and the DB does not support views (Progress OpenEdge).
  • No. Primary keys can not be null.

    From andreasmk2
  • This is not advisable. Could you use a view and map that instead? You could use COALESCE to supply a default if you are stuck with legacy data. We had lots of trouble with composite keys and I imagine null values will cause even more issues.

  • For composite keys (assumed that database allows nulls in PKs) you can have maximum number_of_cols^2 - 1 entries containing nulls, (for example for composite key of 2 columns you can have 3 rows having in their primary key null, the fourth is the PK without nulls).

    From andreasmk2

0 comments:

Post a Comment