悲观锁 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