简体   繁体   中英

Spring JPA save transient entity

in hibernate if I persist new entity it should become managed , moreover it should return the managed entity.

if the entity is detached , the merge will return managed entity but the one that I passed will still detached.

I've tried that in spring boot with hibernate and everything is working except the following case :

User transientUser=new User();
    transientUser.setId(9L);
    User managedTransientUser=userRepository.save(transientUser);

if I set the Id manually ( even with removing the auto generation) the entity that I pass ( transientUser) will still be unmanaged . If I use generation Identity then the returned and passed entity are the same ( the id is null and the DB will auto increment ) is that expected ?

That's simply because you're not calling persist() . You're calling userRepository.save() .

This method tests if the entity is new (by checking if it already has an ID). If it is, it calls persist() . Otherwise it calls merge() . Since your entity already has an ID, it calls merge() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM