All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cedarsoft.gdao.hibernate.HibernateDao Maven / Gradle / Ivy

There is a newer version: 1.0.1
Show newest version
/**
 * Copyright (C) cedarsoft GmbH.
 *
 * Licensed under the GNU General Public License version 3 (the "License")
 * with Classpath Exception; you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *         http://www.cedarsoft.org/gpl3ce
 *         (GPL 3 with Classpath Exception)
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 3 only, as
 * published by the Free Software Foundation. cedarsoft GmbH designates this
 * particular file as subject to the "Classpath" exception as provided
 * by cedarsoft GmbH in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 3 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 3 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact cedarsoft GmbH, 72810 Gomaringen, Germany,
 * or visit www.cedarsoft.com if you need additional information or
 * have any questions.
 */

package com.cedarsoft.gdao.hibernate;

import com.cedarsoft.NullLock;
import com.cedarsoft.gdao.Finder;
import com.cedarsoft.gdao.GenericDao;
import com.cedarsoft.gdao.LockProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.lang.Override;
import java.util.List;
import java.util.concurrent.locks.Lock;

/**
 * Hibernate implementation for {@link GenericDao}.
 * This class is *not* thread safe
 *
 * @param the type
 */
public class HibernateDao extends HibernateDaoSupport implements GenericDao {
  @NonNls
  @NotNull
  private static final Log log = LogFactory.getLog( HibernateDao.class );

  @NotNull
  private final Class type;
  @Nullable
  private final LockProvider lockProvider;

  /**
   * Creates a new instance
   *
   * @param sessionFactory the session factory
   * @param type           the type
   */
  public HibernateDao( @NotNull SessionFactory sessionFactory, @NotNull Class type ) {
    this( sessionFactory, type, null );
  }

  public HibernateDao( @NotNull SessionFactory sessionFactory, @NotNull Class type, @Nullable LockProvider lockProvider ) {
    this.type = type;
    this.lockProvider = lockProvider;
    setSessionFactory( sessionFactory );
  }

  @Nullable
  public LockProvider getLockProvider() {
    return lockProvider;
  }

  @Override
  public final void remove( @NotNull T element ) throws DataAccessException {
    delete( element );
  }

  @Override
  public final void add( @NotNull T element ) {
    saveOrUpdate( element );
  }

  @Override
  public void commit( @NotNull T element ) {
    update( element );
  }

  @Override
  public void setElements( @NotNull List elements ) {
    throw new UnsupportedOperationException( "Not supported for daos" );
  }

  @Override
  @NotNull
  public final List getElements() {
    return findAll();
  }

  @Override
  @NotNull
  public List findAll() {
    return getHibernateTemplate().executeFind( new HibernateCallback() {
      @Override
      public Object doInHibernate( Session session ) throws HibernateException {
        return session.createCriteria( type ).list();
      }
    } );
  }

  @Override
  public int getCount() {
    return ( Integer ) getHibernateTemplate().execute( new HibernateCallback() {
      @Override
      public Object doInHibernate( Session session ) throws HibernateException {
        return session.createCriteria( type ).list().size();
      }
    } );
  }

  @Override
  @NotNull
  public  Long save( @NotNull LT newInstance ) {
    Lock writeLock = getWriteLock( newInstance );
    writeLock.lock();
    try {
      return ( Long ) getHibernateTemplate().save( newInstance );
    } finally {
      writeLock.unlock();
    }
  }

  /**
   * Returns the write lock for the given object
   *
   * @param object the object the write lock is obtained for
   * @return the write lock for the given object or a NULL lock
   */
  @NotNull
  private Lock getWriteLock( @NotNull T object ) {
    if ( lockProvider != null ) {
      return lockProvider.getWriteLock( object );
    } else {
      return NullLock.LOCK;
    }
  }

  @Override
  @NotNull
  public T findById( @NotNull Long id ) throws DataAccessException {
    T found = type.cast( getHibernateTemplate().get( type, id ) );
    if ( found == null ) {
      throw new EmptyResultDataAccessException( 1 );
    }
    return found;
  }

  @Override
  public  void saveOrUpdate( @NotNull LT object ) {
    Lock lock = getWriteLock( object );
    lock.lock();
    try {
      getHibernateTemplate().saveOrUpdate( object );
    } finally {
      lock.unlock();
    }
  }

  @Override
  public  void update( @NotNull LT transientObject ) {
    Lock lock = getWriteLock( transientObject );
    lock.lock();
    try {
      getHibernateTemplate().saveOrUpdate( transientObject );
    } finally {
      lock.unlock();
    }
  }

  @Override
  public  void delete( @NotNull LT persistentObject ) throws DataAccessException {
    Lock lock = getWriteLock( persistentObject );
    lock.lock();
    try {
      getHibernateTemplate().delete( persistentObject );
    } catch ( DataAccessException e ) {
      log.warn( "Error when trying to delete " + persistentObject );
      throw e;
    } finally {
      lock.unlock();
    }
  }

  @Override
  @NotNull
  public  T find( @NotNull final Finder finder ) throws EmptyResultDataAccessException {
    //noinspection unchecked
    return ( T ) getHibernateTemplate().execute( new HibernateCallback() {
      @Override
      @NotNull
      public T doInHibernate( @NotNull Session session ) throws HibernateException {
        return finder.find( session );
      }
    } );
  }

  @Override
  public void shutdown() {
  }

  @Override
  public String toString() {
    return "HibernateDao for: " + type.getName() + ". " + hashCode();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy