Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

java - Are JPA and Hibernate entity identifiers reset to null after a rollback?

What happens with Entities in session if I make rollback ? Do they get back to the state before transaction ? In particular do they get new ids ?

Example:

session.startTransaction();
Entity e = new Entity(); //e.id == null
session.save (e);        //suppose it was ok
session.rollback();      // e.id == ???

Update:

I've made the Hibernate 4 test. After the test the entity has become a new id.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I will simply quote from the JPA implementation (3.3.2 Transaction Rollback):

For both transaction-scoped and extended persistence contexts, transaction rollback causes all pre-exist-ing managed instances and removed instances[31] to become detached. The instances’ state will be the state of the instances at the point at which the transaction was rolled back. Transaction rollback typically causes the persistence context to be in an inconsistent state at the point of rollback. In particular, the state of version attributes and generated state (e.g., generated primary keys) may be inconsistent. Instances that were formerly managed by the persistence context (including new instances that were made persistent in that transaction) may therefore not be reusable in the same manner as other detached objects—for example, they may fail when passed to the merge operation.[32]

This actually means, that it depends whether you have or not an ID right before calling em.rollback() (which depends on FlushMode & JPA implementation). If an ID was assigned, than the ID will remain set. If not, then you will have no ID.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...