1

我试图了解 Hibernate 中的悲观锁定机制(通过 MySQL DB)。

我尝试运行以下示例:

    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){

            }
    }

但是它没有给我一个错误,而是执行得很好。是否有某种我误解的概念。这种行为正常吗?

我能够完美地测试乐观锁定,因此对于悲观锁定是否存在对该概念的一些误解,或者我的代码缺少某些东西。

4

2 回答 2

1

您也在使用单个会话和单个事务。数据库锁是可重入的,否则你最终会自己死锁。

更改您的示例以启动两个会话,每个会话都有自己的事务。然后你会看到第二个事务等待第一个事务释放获取的锁。

于 2015-01-16T05:46:00.557 回答
0

为了澄清这个概念,在石英中生成两个计划的作业,每秒运行一次,以持久保存在您的数据库中。

下面的链接包含代码。

https://github.com/bozorgvar/JTA-Locking/tree/master/src/transaction

检查以下文件:

  • 日程安排.java
  • HelloJob.java
  • HelloJob2.java
于 2015-03-02T18:29:41.577 回答