浏览 6242 次
精华帖 (0) :: 良好帖 (7) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-05-06
hibernate.current_session_context_class = jta/thread/managed //Use thread HibernateUtil.java package org.hibernate.tutorial.util; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class HibernateUtil { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } 在使用的时候大概都是如此调用: private Long createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate); session.save(theEvent); session.getTransaction().commit(); return theEvent.getId(); } 很顺利,跑起来也一切正常。 我有一个查询的需求。就是load一个Object对象需求。代码如下: private Event find(Event event) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); //session.beginTransaction(); Event load = (Event) session.load(Event.class, event.getId()); //session.getTransaction().commit(); return load; } 我一想,就是一普通的load和查询操作,应该不用开闭Transaction了。但是却报异常了: org.hibernate.HibernateException: get is not valid without active transaction 太抓狂了,就一些查询操作也要开闭Transaction。公司有使用过Hiberbate的小伙子说的记得应该是不用的。想想唯一的使用的区别就是得到Session的代码从 HibernateUtil.getSessionFactory().openSession(); 变为了 HibernateUtil.getSessionFactory().getCurrentSession(); 难道是这句HibernateUtil.getSessionFactory().getCurrentSession();有猫腻? Checkout源码,跟进去看,果然: HibernateUtil.getSessionFactory().getCurrentSession()将Session交给一个CurrentSessionContext来处理,根据配置,使用的是ThreadLocalSessionContext这个东东。查看他的源码: public final Session currentSession() throws HibernateException { Session current = existingSession( factory ); if (current == null) { current = buildOrObtainSession(); // register a cleanup synch current.getTransaction().registerSynchronization( buildCleanupSynch() ); // wrap the session in the transaction-protection proxy if ( needsWrapping( current ) ) { current = wrap( current );//Warp Here???? } // then bind it doBind( current, factory ); } return current; } 发现这里的Session已经是不纯洁了,已经成宋祖德嘴里的女明星了。被包了。看看被包的过程, protected Session wrap(Session session) { TransactionProtectionWrapper wrapper = new TransactionProtectionWrapper( session ); Session wrapped = ( Session ) Proxy.newProxyInstance( Session.class.getClassLoader(), SESS_PROXY_INTERFACES, wrapper ); // yick! need this for proper serialization/deserialization handling... wrapper.setWrapped( wrapped ); return wrapped; } 被包的很过分,直接换成代理了,看看代理人的嘴脸,这个代理人是TransactionProtectionWrapper 看看他是用什么好东西包的: /** * {@inheritDoc} */ public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { // If close() is called, guarantee unbind() if ( "close".equals( method.getName()) ) { unbind( realSession.getSessionFactory() ); } else if ( "toString".equals( method.getName() ) || "equals".equals( method.getName() ) || "hashCode".equals( method.getName() ) || "getStatistics".equals( method.getName() ) || "isOpen".equals( method.getName() ) ) { // allow these to go through the the real session no matter what } else if ( !realSession.isOpen() ) { // essentially, if the real session is closed allow any // method call to pass through since the real session // will complain by throwing an appropriate exception; // NOTE that allowing close() above has the same basic effect, // but we capture that there simply to perform the unbind... } else if ( !realSession.getTransaction().isActive() ) { // limit the methods available if no transaction is active if ( "beginTransaction".equals( method.getName() ) || "getTransaction".equals( method.getName() ) || "isTransactionInProgress".equals( method.getName() ) || "setFlushMode".equals( method.getName() ) || "getSessionFactory".equals( method.getName() ) ) { log.trace( "allowing method [" + method.getName() + "] in non-transacted context" ); } else if ( "reconnect".equals( method.getName() ) || "disconnect".equals( method.getName() ) ) { // allow these (deprecated) methods to pass through } else { throw new HibernateException( method.getName() + " is not valid without active transaction" ); } } log.trace( "allowing proxied method [" + method.getName() + "] to proceed to real session" ); return method.invoke( realSession, args ); } catch ( InvocationTargetException e ) { if ( e.getTargetException() instanceof RuntimeException ) { throw ( RuntimeException ) e.getTargetException(); } else { throw e; } } } 呵呵,几乎所有正常的操作都必须在transcation.isActive()条件下才能执行。我要用的get,load,save, saveOrUpdate,list都在此列。 到此为止,算明白了。 寻到根了,Hibernate的理由是: org.hibernate.context.ThreadLocalSessionContext A CurrentSessionContext impl which scopes the notion of current session by the current thread of execution. Unlike the JTA counterpart, threads do not give us a nice hook to perform any type of cleanup making it questionable for this impl to actually generate Session instances. In the interest of usability, it was decided to have this default impl actually generate a session upon first request and then clean it up after the org.hibernate.Transaction associated with that session is committed/rolled-back. In order for ensuring that happens, the sessions generated here are unusable until after Session.beginTransaction() has been called. If close() is called on a session managed by this class, it will be automatically unbound. Additionally, the static bind and unbind methods are provided to allow application code to explicitly control opening and closing of these sessions. This, with some from of interception, is the preferred approach. It also allows easy framework integration and one possible approach for implementing long-sessions. The buildOrObtainSession, isAutoCloseEnabled, isAutoFlushEnabled, getConnectionReleaseMode, and buildCleanupSynch methods are all provided to allow easy subclassing (for long-running session scenarios, for example). Author: Steve Ebersole 用别人的东西得小心,知道他背后干了什么很重要啊。 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2009-05-07
发现Hibernate的使用不容易啊 呵呵
|
|
返回顶楼 | |