001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.spring.hibernate;
016    
017    import com.liferay.portal.kernel.exception.SystemException;
018    import com.liferay.portal.kernel.util.AutoResetThreadLocal;
019    
020    import org.hibernate.Session;
021    
022    /**
023     * @author Shuyang Zhou
024     */
025    public class LastSessionRecorderUtil {
026    
027            public static void syncLastSessionState() throws SystemException {
028                    Session session = _lastSessionThreadLocal.get();
029    
030                    if ((session != null) && session.isOpen()) {
031                            try {
032                                    session.flush();
033                                    session.clear();
034                            }
035                            catch (Exception e) {
036                                    throw new SystemException(e);
037                            }
038                    }
039            }
040    
041            protected static void setLastSession(Session session) {
042                    _lastSessionThreadLocal.set(session);
043            }
044    
045            private static ThreadLocal<Session> _lastSessionThreadLocal =
046                    new AutoResetThreadLocal<Session>(
047                            LastSessionRecorderUtil.class.getName() +
048                                    "._lastSessionThreadLocal");
049    
050    }