DecisionItemDaoBase.java

// license-header java merge-point
//
// Attention: Generated code! Do not modify by hand! hibernate4=true hibernateVersion=4
// Generated by hibernate/SpringHibernateDaoBase.vsl in andromda-spring-cartridge. Do not modify by hand!.
//
package org.andromda.samples.animalquiz.decisiontree;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import org.andromda.samples.animalquiz.PrincipalStore;
import org.andromda.samples.animalquiz.PropertySearch;
import org.andromda.samples.animalquiz.Search;
import org.andromda.spring.PaginationResult;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Transformer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.dao.InvalidDataAccessResourceUsageException;
import org.springframework.stereotype.Repository;

/**
 * <p>
 * Base Spring DAO Class: is able to create, update, remove, load, and find
 * objects of type <code>DecisionItem</code>.
 * </p>
 *
 * @see DecisionItem
 */
@Repository
public abstract class DecisionItemDaoBase
    implements DecisionItemDao
{
    /**
     * For backwards compatibility with HibernateDao method
     * @deprecated Use LogFactory.getLog on each subclass, for the correct class name
     * Apache commons logging logger used by all subclasses
     */
    @Deprecated
    protected Log logger = LogFactory.getLog(DecisionItemDaoBase.class);

    @Resource
    private SessionFactory sessionFactory;
    /**
     * @param sessionFactoryIn
     */
    public void setSessionFactory(SessionFactory sessionFactoryIn) {
        this.sessionFactory = sessionFactoryIn;
    }
    /**
     * @return SessionFactory
     */
    protected SessionFactory getSessionFactory() {
        return this.sessionFactory;
    }
    /**
     * @return currentSession
     */
    protected Session getSession() {
        return this.sessionFactory.getCurrentSession();
    }
    /**
     * For backwards compatibility with HibernateDao method
     * @deprecated Use this.sessionFactory.getCurrentSession() instead
     * @param ignore boolean - always create new session if needed
     * @return currentSession
     */
    @Deprecated
    protected Session getSession(boolean ignore) {
        return this.getSession();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object get(final int transform, final Long id)
    {
        if (id == null)
        {
            throw new IllegalArgumentException(
                "DecisionItem.get - 'id' can not be null");
        }
        final Object entity = this.sessionFactory.getCurrentSession().get(DecisionItemImpl.class, id);
        return transformEntity(transform, (DecisionItem)entity);
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public DecisionItem get(Long id)
    {
        return (DecisionItem)this.get(TRANSFORM_NONE, id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object load(final int transform, final Long id)
    {
        if (id == null)
        {
            throw new IllegalArgumentException(
                "DecisionItem.load - 'id' can not be null");
        }
        final Object entity = this.sessionFactory.getCurrentSession().get(DecisionItemImpl.class, id);
        return transformEntity(transform, (DecisionItem)entity);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DecisionItem load(Long id)
    {
        return (DecisionItem)this.load(TRANSFORM_NONE, id);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({"unchecked"})
    public Collection<DecisionItem> loadAll()
    {
        return (Collection<DecisionItem>) this.loadAll(DecisionItemDao.TRANSFORM_NONE);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> loadAll(final int transform)
    {
        return this.loadAll(transform, -1, -1);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> loadAll(final int pageNumber, final int pageSize)
    {
        return this.loadAll(DecisionItemDao.TRANSFORM_NONE, pageNumber, pageSize);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> loadAll(final int transform, final int pageNumber, final int pageSize)
    {
        final Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(DecisionItemImpl.class);
        if (pageNumber > 0 && pageSize > 0)
        {
            criteria.setFirstResult(this.calculateFirstResult(pageNumber, pageSize));
            criteria.setMaxResults(pageSize);
        }
        final Collection<?> results = criteria.list();
        this.transformEntities(transform, results);
        return results;
    }

    /**
     * firstResult = (pageNumber - 1) * pageSize
     * @param pageNumber
     * @param pageSize
     * @return firstResult
     */
    protected int calculateFirstResult(int pageNumber, int pageSize)
    {
        int firstResult = 0;
        if (pageNumber > 0)
        {
            firstResult = (pageNumber - 1) * pageSize;
        }
        return firstResult;
    }

    /**
     * prePersist event - This method is called before creating the entity
     */
    protected void _prePersist(final DecisionItem decisionItem)
    {
    }
     
    /**
     * postPersist event - This method is called after creating the entity
     */
    protected void _postPersist(final DecisionItem decisionItem)
    {
    }
     
    /**
     * preUpdate event - This method is called before updating the entity
     */
    protected void _preUpdate(final DecisionItem decisionItem)
    {
    }
     
    /**
     * postUpdate event - This method is called after updating the entity
     */
    protected void _postUpdate(final DecisionItem decisionItem)
    {
    }
     
    /**
     * preRemove event - This method is called before deleting the entity
     */
    protected void _preRemove(final DecisionItem decisionItem)
    {
    }
     
    /**
     * postRemove event - This method is called after deleting the entity
     */
    protected void _postRemove(final DecisionItem decisionItem)
    {
    }
     
    /**
     * {@inheritDoc}
     */
    @Override
    public void update(DecisionItem decisionItem)
    {
        if (decisionItem == null)
        {
            throw new IllegalArgumentException(
                "DecisionItem.update - 'decisionItem' can not be null");
        }
        
        //preUpdate event
        _preUpdate(decisionItem);

        this.sessionFactory.getCurrentSession().update(decisionItem);

        //postUpdate event
        _postUpdate(decisionItem);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void update(final Collection<DecisionItem> entities)
    {
        if (entities == null)
        {
            throw new IllegalArgumentException(
                "DecisionItem.update - 'entities' can not be null");
        }
        for (DecisionItem entity : entities)
        {
            update(entity);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void remove(DecisionItem decisionItem)
    {
        if (decisionItem == null)
        {
            throw new IllegalArgumentException(
                "DecisionItem.remove - 'decisionItem' can not be null");
        }
        //preRemove event
        _preRemove(decisionItem);
        
        this.sessionFactory.getCurrentSession().delete(decisionItem);

        //postRemove event
        _postRemove(decisionItem);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void remove(Long id)
    {
        if (id == null)
        {
            throw new IllegalArgumentException(
                "DecisionItem.remove - 'id' can not be null");
        }
        DecisionItem entity = this.get(id);
        if (entity != null)
        {
            this.remove(entity);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void remove(Collection<DecisionItem> entities)
    {
        if (entities == null)
        {
            throw new IllegalArgumentException(
                "DecisionItem.remove - 'entities' can not be null");
        }
        for (DecisionItem entity : entities)
        {
            //preRemove event
            _preRemove(entity);

            this.sessionFactory.getCurrentSession().delete(entity);

            //postRemove event
            _postRemove(entity);
        }
    }
    /**
     * {@inheritDoc}
     */
    @Override
    public DecisionItem findRoot()
        throws DecisionException
    {
        return (DecisionItem)this.findRoot(DecisionItemDao.TRANSFORM_NONE);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object findRoot(final int transform)
        throws DecisionException
    {
        return this.findRoot(transform, "from DecisionItemImpl as decisionItem");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public DecisionItem findRoot(final String queryString)
        throws DecisionException
    {
        return (DecisionItem)this.findRoot(DecisionItemDao.TRANSFORM_NONE, queryString);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object findRoot(final int transform, final String queryString)
        throws DecisionException
    {
        Query queryObject = this.sessionFactory.getCurrentSession().createQuery(queryString);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Set results = new LinkedHashSet(queryObject.list());
            Object result = null;
            if (results.size() > 1)
            {
                throw new InvalidDataAccessResourceUsageException(
                    "More than one instance of 'org.andromda.samples.animalquiz.decisiontree.DecisionItem"
                        + "' was found when executing query --> '" + queryString + "'");
            }
            else if (results.size() == 1)
            {
                result = results.iterator().next();
            }
            if(transform != TRANSFORM_NONE){
                result = transformEntity(transform, (DecisionItem)result);
            }
            return result;
    }

    /**
     * Allows transformation of entities into value objects
     * (or something else for that matter), when the <code>transform</code>
     * flag is set to one of the constants defined in <code>DecisionItemDao</code>, please note
     * that the {@link #TRANSFORM_NONE} constant denotes no transformation, so the entity itself
     * will be returned.
     * <p>
     * This method will return instances of these types:
     * <ul>
     *   <li>{@link DecisionItem} - {@link #TRANSFORM_NONE}</li>
     *   <li>{@link VODecisionItem} - {@link #TRANSFORM_VODECISIONITEM}</li>
     * </ul>
     *
     * If the integer argument value is unknown {@link #TRANSFORM_NONE} is assumed.
     *
     * @param transform one of the constants declared in {@link DecisionItemDao}
     * @param entity an entity that was found
     * @return the transformed entity (i.e. new value object, etc)
     * @see DecisionItemDao#transformEntity(int, DecisionItem)
     */
    @Override
    public Object transformEntity(final int transform, final DecisionItem entity)
    {
        Object target = null;
        if (entity != null)
        {
            switch (transform)
            {
                case TRANSFORM_VODECISIONITEM :
                    target = toVODecisionItem(entity);
                    break;
                case DecisionItemDao.TRANSFORM_NONE : // fall-through
                default:
                    target = entity;
            }
        }
        return target;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void transformEntities(final int transform, final Collection<?> entities)
    {
        switch (transform)
        {
            case TRANSFORM_VODECISIONITEM :
                CollectionUtils.transform(entities, this.VODECISIONITEM_TRANSFORMER);
                break;
            case DecisionItemDao.TRANSFORM_NONE : // fall-through
                default:
                // do nothing;
        }
    }

    /**
     * @see DecisionItemDao#toEntities(Collection)
     */
    @Override
    public void toEntities(final Collection<?> results)
    {
        if (results != null)
        {
            CollectionUtils.transform(results, this.ENTITYTRANSFORMER);
        }
    }

    /**
     * This anonymous transformer is designed to transform report query results
     * (which result in an array of entities) to {@link DecisionItem}
     * using the Jakarta Commons-Collections Transformation API.
     */
    private Transformer ENTITYTRANSFORMER =
        new Transformer()
        {
            @Override
            public Object transform(Object input)
            {
                Object result = null;
                if (input instanceof Object[])
                {
                    final Object[] rows = (Object[])input; 
                    result = toEntity(rows);
                }
                else if (input instanceof DecisionItem)
                {
                    result = input;
                }
                return result;
            }
        };

    /**
     * @param row
     * @return DecisionItem
     */
    protected DecisionItem toEntity(Object[] row)
    {
        DecisionItem target = null;
        if (row != null)
        {
            final int numberOfObjects = row.length;
            for (int ctr = 0; ctr < numberOfObjects; ctr++)
            {
                final Object object = row[ctr];
                if (object instanceof DecisionItem)
                {
                    target = (DecisionItem)object;
                    break;
                }
            }
        }
        return target;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({"unchecked"})
    public final Collection<VODecisionItem> toVODecisionItemCollection(Collection<DecisionItem> entities)
    {
        if (entities == null)
        {
            return null;
        }
        else
        {
            @SuppressWarnings("rawtypes")
            Collection result = new ArrayList(entities);
            CollectionUtils.transform(result, this.VODECISIONITEM_TRANSFORMER);
            return (Collection<VODecisionItem>) result;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public final VODecisionItem[] toVODecisionItemArray(Collection<?> entities)
    {
        VODecisionItem[] result = null;
        if (entities != null)
        {
        @SuppressWarnings("rawtypes")
            final Collection collection = new ArrayList(entities);
            this.toVODecisionItemCollection(collection);
            result = (VODecisionItem[]) collection.toArray(new VODecisionItem[collection.size()]);
        }
        return result;
    }

    /**
     * Default implementation for transforming the results of a report query into a value object. This
     * implementation exists for convenience reasons only. It needs only be overridden in the
     * {@link DecisionItemDaoImpl} class if you intend to use reporting queries.
     * @param row
     * @return toVODecisionItem(this.toEntity(row))
     * @see DecisionItemDao#toVODecisionItem(DecisionItem)
     */
    protected VODecisionItem toVODecisionItem(Object[] row)
    {
        return this.toVODecisionItem(this.toEntity(row));
    }

    /**
     * This anonymous transformer is designed to transform entities or report query results
     * (which result in an array of objects) to {@link VODecisionItem}
     * using the Jakarta Commons-Collections Transformation API.
     */
    private Transformer VODECISIONITEM_TRANSFORMER =
        new Transformer()
        {
            @Override
            public Object transform(Object input)
            {
                Object result = null;
                if (input instanceof DecisionItem)
                {
                    final DecisionItem entity = (DecisionItem)input;
                    result = toVODecisionItem(entity);
                }
                else if (input instanceof Object[])
                {
                    final Object[] rows = (Object[])input;
                    result = toVODecisionItem(rows);
                }
                return result;
            }
        };

    /**
     * {@inheritDoc}
     */
    @Override
    public final void vODecisionItemToEntityCollection(Collection<?> instances)
    {
        if (instances != null)
        {
            for (final Iterator<?> iterator = instances.iterator(); iterator.hasNext();)
            {
                // - remove an objects that are null or not of the correct instance
                if (!(iterator.next() instanceof VODecisionItem))
                {
                    iterator.remove();
                }
            }
            CollectionUtils.transform(instances, this.VODecisionItemToEntityTransformer);
        }
    }

    private final Transformer VODecisionItemToEntityTransformer =
        new Transformer()
        {
            @Override
            public Object transform(Object input)
            {
                return vODecisionItemToEntity((VODecisionItem)input);
            }
        };


    /**
     * {@inheritDoc}
     */
    @Override
    public void toVODecisionItem(
        DecisionItem source,
        VODecisionItem target)
    {
        target.setId(source.getId());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public VODecisionItem toVODecisionItem(final DecisionItem entity)
    {
        VODecisionItem target = null;
        if (entity != null)
        {
            target =  new VODecisionItem();
            this.toVODecisionItem(entity, target);
        }
        return target;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void vODecisionItemToEntity(
        VODecisionItem source,
        DecisionItem target,
        boolean copyIfNull)
    {
    }

    /**
     * Gets the current <code>principal</code> if one has been set,
     * otherwise returns <code>null</code>.
     *
     * @return the current principal
     */
    protected Principal getPrincipal()
    {
        return PrincipalStore.get();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings({ "unchecked" })
    public PaginationResult search(final int transform, final int pageNumber, final int pageSize, final Search search)
    {
        search.setPageNumber(pageNumber);
        search.setPageSize(pageSize);
        final PropertySearch propertySearch = new PropertySearch(
            this.sessionFactory.getCurrentSession(), DecisionItemImpl.class, search);
        final List results = propertySearch.executeAsList();
        this.transformEntities(transform, results);
        return new PaginationResult(results.toArray(new Object[results.size()]), propertySearch.getTotalCount());
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public PaginationResult search(final int pageNumber, final int pageSize, final Search search)
    {
        return this.search(DecisionItemDao.TRANSFORM_NONE, pageNumber, pageSize, search);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Collection<?> search(final int transform, final Search search)
    {
        final PropertySearch propertySearch = new PropertySearch(
            this.sessionFactory.getCurrentSession(), DecisionItemImpl.class, search);
        final Collection<?> results = propertySearch.executeAsList();
        this.transformEntities(transform, results);
        return results;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public Collection<DecisionItem> search(final Search search)
    {
        return (Collection<DecisionItem>) this.search(DecisionItemDao.TRANSFORM_NONE, search);
    }

    /**
     * Executes and returns the given Hibernate queryObject as a {@link PaginationResult} instance.
     * @param queryObject
     * @param transform
     * @param pageNumber
     * @param pageSize
     * @return PaginationResult
     */
    @SuppressWarnings({ "unchecked" })
    protected PaginationResult getPaginationResult(
        final Query queryObject,
        final int transform, int pageNumber, int pageSize)
    {
        final ScrollableResults scrollableResults = queryObject.scroll();
        scrollableResults.last();
        int totalCount = scrollableResults.getRowNumber();
        totalCount = totalCount >= 0 ? totalCount + 1 : 0;
        if (pageNumber > 0 && pageSize > 0)
        {
            queryObject.setFirstResult(this.calculateFirstResult(pageNumber, pageSize));
            queryObject.setMaxResults(pageSize);
        }
        // Unchecked transformation because Set object is reused, cannot be strongly typed.
        @SuppressWarnings("rawtypes")
        Collection results = new ArrayList(queryObject.list());
        transformEntities(transform, results);
        return new PaginationResult(results.toArray(new Object[results.size()]), totalCount);
    }


    /**
     * Create or Update the <code>decisionItem</code> instance in the persistent store.
     * @param decisionItem
     */
    @Override
    public DecisionItem createOrUpdate(DecisionItem decisionItem)
    {
        if(decisionItem.getId() == null)
        {
            throw new RuntimeException("Abstract entity DecisionItem cannot be created.");
        }
        else
        {
            this.update(decisionItem);
            return decisionItem;
        }
    }
    
    // spring-hibernate-dao-base merge-point
}