2015-01-16 81 views
1

我想了解Hibernate中的悲觀鎖定機制(通過MySQL數據庫)。休眠悲觀鎖定模式

我試圖運行下面的例子:

public static void main(String[] args) { 
    SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
      Session session = sessionFactory.openSession(); 
    Student student = null; 
    Student studentTwo = null; 
      try { 
       session.beginTransaction();  
       student = (Student) session.get(Student.class, 1, LockMode.PESSIMISTIC_WRITE); 
//I was hoping this line would thrown an error 
       studentTwo = (Student) session.get(Student.class, 1, LockMode.PESSIMISTIC_WRITE);    
       System.out.println(student.getName()); 
       System.out.println(studentTwo.getName()); 
       student.setName("John Doe"); 
       session.getTransaction().commit(); 

       session.close(); 
      }catch(HibernateException ex){ 

      } 
    } 

而是讓我一個錯誤,它只是執行罰款。是否有某種我誤解的概念。這種行爲是否正常?

我能夠測試樂觀鎖定非常好,因此對於悲觀鎖定是否存在對概念的一些誤解或者存在某些代碼丟失的情況。

回答

1

您也正在使用單個會話和單個事務。 database locks是可重入的,否則你最終會自行死鎖。

更改您的示例以啓動兩個會話,每個會話都有自己的事務。然後你會看到第二個事務等待第一個釋放獲取的鎖。

+0

好吧,讓我來試試。非常感謝。 –

+0

是的,嘗試訪問使用兩個會話做了伎倆。非常感謝解釋。 –