tags:

views:

44

answers:

1

If i use ex.merge(obj), now if in object obj i set the primary key to a value which is not present in database, will it create a new record or will it throw an exception?

for example

if obj with pk val = 19 doesnot exist in database,and i set
obj.setPk(20);
obj.setName("nm");

em.merge(obj)  // will this throw an exception or create a new record?`enter code here`
+3  A: 

It will create a new record:

  • if the entity is already in the persistence context (session), no action is taken, except for cascades

  • if the entity is detached, a copy (object') is returned, which is attached (managed)

  • if the entity is transient (new instance), it is saved and a persistent (and managed) copy is returned

Bozho
+1 nice explanation
org.life.java
I copied it from a comment I've written on a generic Dao of mine, because it is not so straightforward. I remember I had to read the spec a few times before realizing what's happening :)
Bozho