Am Freitag, 10. August 2012 11:45:22 UTC+2 schrieb (unbekannt):

>> Well, Hibernate solves this like so: If the PK is null, the identity 
>> generator is started to assign a PK (well, I simplify but you get the idea) 
>> and an INSERT will happen. If the PK is not null, it will UPDATE.
>>
> I guess it would work if the PK is based on a sequence, but it is not 
> uncommon to have non auto-increment PKs, how would hibernate do it in this 
> case?
>

When store() is called, Hibernate notices that the PK is NULL (or 0L if you 
use long) and it remembers that bit of information. Depending on the type 
of PK generator, it will either generate a new PK and store it in the field 
(from this point on, H. doesn't need the PK anymore - it has a boolean flag 
which tells it whether to UPDATE or INSERT) or it will store the record 
with a NULL PK and read the new PK from the DB after the INSERT and put 
that into the field.
 

> This feels natural because it uses the assumption that you can't have a PK 
>> unless the record has been read from the DB. And if you have a PK, then the 
>> DB must already know about it.
>>
> Again, if my primary key is a user name, an email, a region or some 
> shipping code, I'd be unable to insert...
>

I always run into problems with natural PKs, so I'm not using them.

Regards,

A. Digulla

Reply via email to