spring - How to explictly state that an Entity is new (transient) in JPA? -


i using spring data jparepository, hibernate jpa provider.

normally when working directly hibernate, decision between entitymanager#persist() , entitymanager#save() programmer. spring data repositories, there save(). not want discuss pros , cons here. let consider following, simple base class:

@mappedsuperclass public abstract class persistableobject {      @id     private string id;      public persistableobject(){         this.id = uuid.randomuuid().tostring();     }      // hashcode() , equals() implemented based on equality of 'id' } 

using base class, spring data repository cannot tell entities "new" (have not been saved db yet), regular check id == null not work in case, because uuids eagerly assigned ensure correctness of equals() , hashcode(). repository seems invoke entitymanager#merge() - inefficient transient entities.

the question is: how tell jpa (or spring data) entity new, such uses entitymanager#persist() instead of #merge() if possible?

i thinking along these lines (using jpa lifecycle callbacks):

@mappedsuperclass public abstract class persistableobject {       @transient      private boolean isnew = true; // default, treat entity new       @postload      private void loaded(){          // loaded entity never new          this.isnew = false;      }       @postpersist      private void saved(){          // saved entity not new anymore          this.isnew = false;      }       // how jpa (or spring data) use method?      public boolean isnew(){          return this.isnew;      }       // other properties, constructor, hashcode() , equals same above  } 

maybe should add @version column:

@version private long version 

in case of new entity null


Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -