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 */ 022package org.granite.tide.hibernate4; 023 024import java.io.Serializable; 025 026import org.granite.tide.TideTransactionManager; 027import org.granite.tide.data.AbstractTidePersistenceManager; 028import org.granite.util.Entity; 029import org.hibernate.Query; 030import org.hibernate.SessionFactory; 031 032/** 033 * Responsible for attaching a session with the persistence mangager 034 * @author cingram 035 * 036 */ 037public class HibernatePersistenceManager extends AbstractTidePersistenceManager { 038 039 private SessionFactory sessionFactory; 040 041 042 public HibernatePersistenceManager(TideTransactionManager tm) { 043 super(tm); 044 } 045 046 public HibernatePersistenceManager(SessionFactory sf) { 047 super(null); 048 this.sessionFactory = sf; 049 } 050 051 public HibernatePersistenceManager(SessionFactory sf, TideTransactionManager tm) { 052 super(tm); 053 this.sessionFactory = sf; 054 } 055 056 @Override 057 public void close() { 058 } 059 060 /** 061 * attaches the entity to the JPA context. 062 * @return the attached entity 063 */ 064 @Override 065 public Object fetchEntity(Object entity, String[] fetch) { 066 Entity tideEntity = new Entity(entity); 067 Serializable id = (Serializable)tideEntity.getIdentifier(); 068 069 if (id == null) 070 return null; 071 072 if (fetch == null) 073 return sessionFactory.getCurrentSession().load(entity.getClass(), id); 074 075 for (String f : fetch) { 076 Query q = sessionFactory.getCurrentSession().createQuery("select e from " + entity.getClass().getName() + " e left join fetch e." + f + " where e = :entity"); 077 q.setParameter("entity", entity); 078 entity = q.uniqueResult(); 079 } 080 return entity; 081 } 082}