001 /*
002 GRANITE DATA SERVICES
003 Copyright (C) 2011 GRANITE DATA SERVICES S.A.S.
004
005 This file is part of Granite Data Services.
006
007 Granite Data Services is free software; you can redistribute it and/or modify
008 it under the terms of the GNU Library General Public License as published by
009 the Free Software Foundation; either version 2 of the License, or (at your
010 option) any later version.
011
012 Granite Data Services is distributed in the hope that it will be useful, but
013 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
014 FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License
015 for more details.
016
017 You should have received a copy of the GNU Library General Public License
018 along with this library; if not, see <http://www.gnu.org/licenses/>.
019 */
020
021 package org.granite.tide.hibernate;
022
023 import java.io.Serializable;
024 import java.util.List;
025
026 import org.granite.logging.Logger;
027 import org.granite.tide.TideTransactionManager;
028 import org.granite.tide.data.AbstractTidePersistenceManager;
029 import org.granite.util.Entity;
030 import org.hibernate.Query;
031 import org.hibernate.SessionFactory;
032
033 /**
034 * Responsible for attaching a session with the persistence mangager
035 * @author cingram
036 *
037 */
038 public class HibernatePersistenceManager extends AbstractTidePersistenceManager {
039
040 private static final Logger log = Logger.getLogger(HibernatePersistenceManager.class);
041
042 private SessionFactory sessionFactory;
043
044
045 public HibernatePersistenceManager(TideTransactionManager tm) {
046 super(tm);
047 }
048
049 public HibernatePersistenceManager(SessionFactory sf) {
050 super(null);
051 this.sessionFactory = sf;
052 }
053
054 public HibernatePersistenceManager(SessionFactory sf, TideTransactionManager tm) {
055 super(tm);
056 this.sessionFactory = sf;
057 }
058
059 @Override
060 public void close() {
061 }
062
063 /**
064 * attaches the entity to the JPA context.
065 * @return the attached entity
066 */
067 @Override
068 public Object fetchEntity(Object entity, String[] fetch) {
069 Entity tideEntity = new Entity(entity);
070 Serializable id = (Serializable)tideEntity.getIdentifier();
071
072 if (id == null)
073 return null;
074
075 if (fetch == null)
076 return sessionFactory.getCurrentSession().load(entity.getClass(), id);
077
078 for (String f : fetch) {
079 Query q = sessionFactory.getCurrentSession().createQuery("select e from " + entity.getClass().getName() + " e left join fetch e." + f + " where e = :entity");
080 q.setParameter("entity", entity);
081 List<?> results = q.list();
082 if (!results.isEmpty())
083 entity = results.get(0);
084 else
085 log.warn("Could not find entity %s to initialize, id: %s", entity.getClass().getName(), id);
086 }
087 return entity;
088 }
089 }