001 // Copyright 2007, 2008 The Apache Software Foundation
002 //
003 // Licensed under the Apache License, Version 2.0 (the "License");
004 // you may not use this file except in compliance with the License.
005 // You may obtain a copy of the License at
006 //
007 // http://www.apache.org/licenses/LICENSE-2.0
008 //
009 // Unless required by applicable law or agreed to in writing, software
010 // distributed under the License is distributed on an "AS IS" BASIS,
011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012 // See the License for the specific language governing permissions and
013 // limitations under the License.
014
015 package org.tynamo.jpa.internal;
016
017 import javax.persistence.EntityManager;
018 import javax.persistence.EntityTransaction;
019
020 import org.apache.tapestry5.ioc.services.ThreadCleanupListener;
021
022 import org.tynamo.jpa.JPAEntityManagerSource;
023 import org.tynamo.jpa.JPATransactionManager;
024
025 public class JPATransactionManagerImpl implements JPATransactionManager, ThreadCleanupListener
026 {
027 private final EntityManager entityManager;
028
029 private EntityTransaction transaction;
030
031 public JPATransactionManagerImpl(JPAEntityManagerSource source)
032 {
033 entityManager = source.create();
034
035 startNewTransaction();
036 }
037
038 private void startNewTransaction()
039 {
040 // transaction = session.beginTransaction();
041 transaction = entityManager.getTransaction();
042 transaction.begin();
043 }
044
045 public void abort()
046 {
047 transaction.rollback();
048 startNewTransaction();
049 }
050
051 public void commit()
052 {
053 transaction.commit();
054 startNewTransaction();
055 }
056
057 public EntityManager getEntityManager()
058 {
059 return entityManager;
060 }
061
062 /**
063 * Rollsback the transaction at the end of the request, then closes the session. This means that
064 * any uncommitted changes are lost; code should inject the HSM and invoke {@link #commit()}
065 * after making any changes, if they should persist.
066 */
067 public void threadDidCleanup()
068 {
069 transaction.rollback();
070
071 entityManager.close();
072 }
073 }