what is the purpose of session.lock method in Hibernate

前端 未结 1 1290
萌比男神i
萌比男神i 2020-12-28 20:07

I am going through lock method of hibernate. I did not get what we are trying to achieve through this method.

 p1  = (Person)session. get(Person.class,1);//         


        
1条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 20:44

    The different lock-modes are meant for preventing the entity from being modified and read from multiple sources simultaneously, see the documentation entry about pessimistic locking for details. In my experience, these are rarely needed, as the database isolation level usually takes care of locking as needed:

    It is not intended that users spend much time worrying about locking strategies. It is usually enough to specify an isolation level for the JDBC connections and then simply let the database do all the work. However, advanced users may wish to obtain exclusive pessimistic locks or re-obtain locks at the start of a new transaction.

    As for the "reassociating a transient instance with the session" (I actually think they mean detached instance?), consider the following picture (Hibernate entity lifecycle):

    Hibernate entity lifecycle

    This is the description from Hibernate community documentation:

    Hibernate defines and supports the following object states:

    • Transient - an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition).
    • Persistent - a persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.
    • Detached - a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

    0 讨论(0)
提交回复
热议问题