- package com;
- import org.hibernate.LockMode;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.AnnotationConfiguration;
- import org.hibernate.cfg.Configuration;
- public class ThreadTest {
- private static Session session = HibernateUtil.currentSession();
- private class Lock1 implements Runnable {
- public void run() {
- // TODO Auto-generated method stub
- Transaction t = session.beginTransaction();
- System.out.println("线程1查询中。。。加锁");
- // 线程1加锁查询
- Employee employee = (Employee) session.get(Employee.class, 2,
- LockMode.UPGRADE);
- try {
- Thread.sleep(10000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- t.commit();
- session.close();
- System.out.println("更新完成,减锁");
- }
- }
- private class Lock2 implements Runnable {
- public void run() {
- // TODO Auto-generated method stub
- Transaction t = session.beginTransaction();
- System.out.println("线程2查询中。。。。。");
- Employee employee = (Employee) session.get(Employee.class, 2);
- System.out.println("线程2更新中。。。。。");
- employee.setEmployeeName("飞飞刘");
- session.update(employee);
- t.commit();
- session.close();
- }
- }
- public static void main(String[] args) {
- ThreadTest t = new ThreadTest();
- Lock1 l1 = t.new Lock1();
- Lock2 l2 = t.new Lock2();
- Thread thread1 = new Thread(l1);
- Thread thread2 = new Thread(l2);
- thread1.start();
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- thread2.start();
- }
- }
hibernate 加锁
最新推荐文章于 2022-03-05 11:13:38 发布
该博客通过一个示例展示了在Hibernate中如何使用LockMode.UPGRADE进行加锁操作,以防止并发控制下的数据不一致。线程1先进行加锁查询,然后休眠10秒,线程2在此期间尝试更新数据,但在加锁机制下被阻塞,直到线程1释放锁。此示例解释了Hibernate的加锁策略在多线程环境中的应用。
975

被折叠的 条评论
为什么被折叠?



