2010年6月14日 星期一

LockMode in DAO of Hibernate

public ProfileVO getProfilebyLoginIdLockMode(final String loginId){
ProfileVO vo = null;
List list = (List)this.getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(org.hibernate.Session session) throws HibernateException, SQLException {
Criteria cri=session.createCriteria(ProfileVO.class,"p");
cri.add(Restrictions.eq("p.loginId", loginId)).setLockMode(LockMode.FORCE);
return cri.list();
}
});

if(list.size()>0){
vo = (ProfileVO)list.get(0);
}
return vo;
}

do not use the following method , because it will get a new persistent context and lock will be failure !

...
Session session = this.getHibernateTemplate().getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from ProfileVO p where p.loginId='"+loginId+"'").setLockMode("p", LockMode.FORCE);
List list1 = query.list();

if(list1.size()>0){
vo = (ProfileVO)list1.get(0);
}
tx.commit();
session.close();

沒有留言:

張貼留言

AI 時代的影響(2026-10-24的心得)

  寫了半個世紀程式、 曾出版《Clean Code》教全世界工程師把程式碼寫乾淨的 Robert C. Martin(Uncle Bob), 最近公開表示他已經有超過 95% 的時間不再逐行閱讀 AI 寫的程式碼。 一位一生都在強調「程式碼是寫給人讀的」宗師級人物,何以敢做出...