001    /**
002     *   GRANITE DATA SERVICES
003     *   Copyright (C) 2006-2013 GRANITE DATA SERVICES S.A.S.
004     *
005     *   This file is part of the Granite Data Services Platform.
006     *
007     *   Granite Data Services is free software; you can redistribute it and/or
008     *   modify it under the terms of the GNU Lesser General Public
009     *   License as published by the Free Software Foundation; either
010     *   version 2.1 of the License, or (at your option) any later version.
011     *
012     *   Granite Data Services is distributed in the hope that it will be useful,
013     *   but WITHOUT ANY WARRANTY; without even the implied warranty of
014     *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
015     *   General Public License for more details.
016     *
017     *   You should have received a copy of the GNU Lesser General Public
018     *   License along with this library; if not, write to the Free Software
019     *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
020     *   USA, or see <http://www.gnu.org/licenses/>.
021     */
022    package org.granite.tide.data;
023    
024    import java.io.Serializable;
025    import java.util.List;
026    
027    import javax.persistence.*;
028    
029    import org.granite.logging.Logger;
030    import org.granite.tide.TideTransactionManager;
031    
032    
033    /**
034     * Responsible for attaching a entity with the entity mangager
035     * @author cingram
036     *
037     */
038    public class JPAPersistenceManager extends AbstractTidePersistenceManager implements TideTransactionPersistenceManager {
039            
040            private static final Logger log = Logger.getLogger(JPAPersistenceManager.class);
041            
042            protected EntityManager entityManager;
043            protected EntityManagerFactory entityManagerFactory;
044            protected boolean shouldCloseEntityManager = false;
045    
046            
047            public JPAPersistenceManager(TideTransactionManager tm) {
048                    super(tm);
049            }
050    
051            public JPAPersistenceManager(EntityManager em) {
052                    this(em, null);
053            }
054            
055            public JPAPersistenceManager(EntityManager em, TideTransactionManager tm) {
056                    super(tm != null ? tm : new JPATransactionManager());
057                    
058            if (em == null)
059                    throw new RuntimeException("entity manager cannot be null");
060            
061            this.entityManager =  em;
062            }
063            
064            public JPAPersistenceManager(EntityManagerFactory emf) {
065                    this(emf, null);
066            }
067            
068            public JPAPersistenceManager(EntityManagerFactory emf, TideTransactionManager tm) {
069                    super(tm != null ? tm : new JPATransactionManager());
070                    
071            if (emf == null)
072                    throw new RuntimeException("entity manager factory cannot be null");
073            
074            this.entityManagerFactory = emf;
075            }
076            
077            public Object getCurrentTransaction() {
078                    initEntityManager();
079                EntityTransaction et = entityManager.getTransaction();   // Try to get a local resource transaction
080                et.begin();
081                return et;
082            }
083            
084            protected void initEntityManager() {
085                    if (this.entityManager != null)
086                            return;
087            this.entityManager = entityManagerFactory.createEntityManager();
088            shouldCloseEntityManager = true;
089            }
090            
091            @Override
092            public void close() {
093                    if (shouldCloseEntityManager && this.entityManager != null)
094                            this.entityManager.close();
095            }
096            
097            
098        /**
099         * Finds the entity with the JPA context.
100         * @return the entity with the JPA context.
101         */
102            @Override
103            public Object fetchEntity(Object entity, String[] fetch) {
104                    org.granite.util.Entity tideEntity = new org.granite.util.Entity(entity);
105                    Serializable id = (Serializable)tideEntity.getIdentifier();
106                    
107            if (id == null)
108                return null;
109            
110            initEntityManager();
111            
112            if (fetch == null || entityManager.getDelegate().getClass().getName().indexOf(".hibernate.") < 0)
113                    return entityManager.find(entity.getClass(), id);
114            
115            for (String f : fetch) {
116                    Query q = entityManager.createQuery("select e from " + entity.getClass().getName() + " e left join fetch e." + f + " where e = :entity");
117                    q.setParameter("entity", entity);
118                    List<?> results = q.getResultList();
119                    if (!results.isEmpty())
120                            entity = results.get(0);
121                    else
122                            log.warn("Could not find entity %s to initialize, id: %s", entity.getClass().getName(), id);  
123            }
124            return entity;
125            }
126    
127    }