Hibernate中实体的三种状态
刚刚查看了一下Hibernate的DOC,发现里面也讲到了Hibernate实体的三种状态,下面是官方的解释:
ThemainfunctionoftheSessionistooffercreate,readanddeleteoperationsforinstancesofmappedentityclasses.Instancesmayexistinoneofthreestates:
transient:neverpersistent,notassociatedwithanySession
persistent:associatedwithauniqueSession
detached:previouslypersistent,notassociatedwithanySession
Transientinstancesmaybemadepersistentbycallingsave(),persist()orsaveOrUpdate().Persistentinstancesmaybemadetransientbycallingdelete().Anyinstancereturnedbyaget()orload()methodispersistent.Detachedinstancesmaybemadepersistentbycallingupdate(),saveOrUpdate(),lock()orreplicate().Thestateofatransientordetachedinstancemayalsobemadepersistentasanewpersistentinstancebycallingmerge().
save()andpersist()resultinanSQLINSERT,delete()inanSQLDELETEandupdate()ormerge()inanSQLUPDATE.ChangestopersistentinstancesaredetectedatflushtimeandalsoresultinanSQLUPDATE.saveOrUpdate()andreplicate()resultineitheranINSERToranUPDATE.
Itisnotintendedthatimplementorsbethreadsafe.Insteadeachthread/transactionshouldobtainitsowninstancefromaSessionFactory.
ASessioninstanceisserializableifitspersistentclassesareserializable.
Atypicaltransactionshouldusethefollowingidiom:
Sessionsess=factory.openSession();
Transactiontx;
try{
tx=sess.beginTransaction();
//dosomework
...
tx.commit();
}
catch(Exceptione){
if(tx!=null)tx.rollback();
throwe;
}
finally{
sess.close();
}
IftheSessionthrowsanexception,thetransactionmustberolledbackandthesessiondiscarded.TheinternalstateoftheSessionmightnotbeconsistentwiththedatabaseaftertheexceptionoccurs.
关于这三种状态,网上已经有很多解释,不过我觉得还是看官方的权威