Question

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.

Was it helpful?

Solution

No. Primary keys can not be null.

OTHER TIPS

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).

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

You wont get error but Hibernate wont be able to map those rows with NULL value for composite column to your Entity. That means you get entity with NULL values in result.

Unfortunatly, no. I either had to use a workaround:

I used composit Id for a view(! not table) where rows can be identified by 2 cols exactly (A, B). Although one of the cols (B) can have null values as well as positive integers. So my workaround is that i created a new col in the view: "BKey" and my view is written as if B is null then value of BKey is -1 else BKey = B. (Only positive integers occour in B and null). I also changed my composit id implementation to use BKey instead of B. Hope it helps for somebody..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top