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
021package org.granite.tide.seam.lazy;
022
023import java.io.Serializable;
024
025import org.hibernate.Query;
026import org.hibernate.Session;
027import org.jboss.seam.Component;
028import org.jboss.seam.Entity;
029
030/**
031 * Manager responsible for looking up the Hibernate Session for the
032 * passed in SessionManagerName
033 * @author CIngram
034 */
035public class SeamHibernateManager extends HibernateContextManager  {
036        
037        private String sessionManagerName = null;
038        private Session session = null;
039
040        public SeamHibernateManager(String sessionManagerName) {
041                this.sessionManagerName = sessionManagerName;
042        }
043        
044
045        /**
046         * Attach the passed in entity with the HibernateManager stored 
047         * in Seam.
048         * @param entity
049         * @return the attached hibernate object
050         */
051    @Override
052    public Object fetchEntity(Object entity, String[] fetch) {
053        Serializable id = (Serializable)Entity.forClass(entity.getClass()).getIdentifier(entity);
054        if (id == null)
055            return null;
056        
057        this.session = (Session)Component.getInstance(sessionManagerName);
058        
059        if (fetch == null)
060                return session.get(entity.getClass(), id);
061        
062        for (String f : fetch) {
063                Query q = session.createQuery("select e from " + entity.getClass().getName() + " e left join fetch e." + f + " where e = :entity");
064                q.setParameter("entity", entity);
065                entity = q.uniqueResult();
066        }
067        return entity;
068    }
069        
070        /**
071         * Disconnects from the current hibernate session.
072         */
073        @Override
074        protected void disconnectSession() {
075                session.disconnect();
076        }
077}