• 悲观锁 HibernateTest.java


    HibernateTest.java

    代码:

    /**
     *
     */
    package com.b510.examplex;

    import java.util.List;

    import org.hibernate.LockMode;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.Transaction;

    /**
     *
     * @author XHW
     *
     * @date 2011-7-8
     *
     */
    public class HibernateTest {

     /**
      * @param args
      */
     public static void main(String[] args) {
      HibernateTest test = new HibernateTest();
      test.testLockMode();
     }

     public void testLockMode() {
      Session session = HibernateSessionFactoryUtil.getSessionFactory()
        .openSession();
      session.beginTransaction();
      
      Query query=session.createQuery("from Guestbook gb");
      //设置为“悲观锁”   悲观地认为每次读读取或修改数据库数据时,其他的事务也在并发访问相同的数据          <具有很强的排他性>
      query.setLockMode("gb", LockMode.UPGRADE);
      List<Guestbook> list=query.list();
      session.getTransaction().commit();
      
      for(Guestbook gb:list){
       System.out.println(gb.getId());
       System.out.println(gb.getName());
       System.out.println(gb.getTitle());
       System.out.println(gb.getEmail());
      }
      
     }

    }

    运行效果:

    没有加“悲观锁”的效果:

    sql语句:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate: 
        select
            guestbook0_.id as id2_,
            guestbook0_.name as name2_,
            guestbook0_.email as email2_,
            guestbook0_.phone as phone2_,
            guestbook0_.title as title2_,
            guestbook0_.content as content2_,
            guestbook0_.created_time as created7_2_
        from
            users.guestbook guestbook0_
    1
    Hongten
    hello world!
    hongtenzone@foxmail.com

    现在加入“悲观锁”

    sql语句:

    log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
    log4j:WARN Please initialize the log4j system properly.
    Hibernate:
        select
            guestbook0_.id as id2_,
            guestbook0_.name as name2_,
            guestbook0_.email as email2_,
            guestbook0_.phone as phone2_,
            guestbook0_.title as title2_,
            guestbook0_.content as content2_,
            guestbook0_.created_time as created7_2_
        from
            users.guestbook guestbook0_ for update
               
    1
    Hongten
    hello world!
    hongtenzone@foxmail.com

  • 相关阅读:
    Oracle跟踪生成及Tkprof分析性能实战(附实战Demo)系列一
    sqlserver查看锁及解锁
    ETL利器Kettle实战应用解析系列二 【应用场景和实战DEMO下载】
    利用反射从程序集dll中动态调用方法(附demo下载)
    ETL利器Kettle实战应用解析系列三 【ETL后台进程执行配置方式】
    分享一款Web压力测试工具Pylot
    stark组件前戏之以上知识点整合应用示例
    rbac组件权限分配
    rbac组件权限分配之权限批量操作
    stark组件开发之自动生成URL
  • 原文地址:https://www.cnblogs.com/hongten/p/2101491.html
Copyright © 2020-2023  润新知