001    /**
002     * Copyright (c) 2000-present 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.transaction.NewTransactionLifecycleListener;
019    import com.liferay.portal.kernel.transaction.TransactionAttribute;
020    import com.liferay.portal.kernel.transaction.TransactionLifecycleListener;
021    import com.liferay.portal.kernel.transaction.TransactionStatus;
022    import com.liferay.portal.kernel.util.AutoResetThreadLocal;
023    
024    import org.hibernate.Session;
025    
026    /**
027     * @author Shuyang Zhou
028     */
029    public class LastSessionRecorderUtil {
030    
031            public static final TransactionLifecycleListener
032                    TRANSACTION_LIFECYCLE_LISTENER = new NewTransactionLifecycleListener() {
033    
034                            @Override
035                            protected void doCreated(
036                                    TransactionAttribute transactionAttribute,
037                                    TransactionStatus transactionStatus) {
038    
039                                    syncLastSessionState();
040                            }
041    
042                    };
043    
044            public static void syncLastSessionState() {
045                    Session session = _lastSessionThreadLocal.get();
046    
047                    if ((session != null) && session.isOpen()) {
048                            try {
049                                    session.flush();
050                                    session.clear();
051                            }
052                            catch (Exception e) {
053                                    throw new SystemException(e);
054                            }
055                    }
056            }
057    
058            protected static void setLastSession(Session session) {
059                    _lastSessionThreadLocal.set(session);
060            }
061    
062            private static final ThreadLocal<Session> _lastSessionThreadLocal =
063                    new AutoResetThreadLocal<Session>(
064                            LastSessionRecorderUtil.class.getName() +
065                                    "._lastSessionThreadLocal");
066    
067    }