我试图了解 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){
}
}
但是它没有给我一个错误,而是执行得很好。是否有某种我误解的概念。这种行为正常吗?
我能够完美地测试乐观锁定,因此对于悲观锁定是否存在对该概念的一些误解,或者我的代码缺少某些东西。