restoring head
[mir.git] / source / org / codecoop / mir / core / dao / hibernate / AbstractDAO.java
diff --git a/source/org/codecoop/mir/core/dao/hibernate/AbstractDAO.java b/source/org/codecoop/mir/core/dao/hibernate/AbstractDAO.java
new file mode 100755 (executable)
index 0000000..faebe06
--- /dev/null
@@ -0,0 +1,434 @@
+/*
+ * Copyright (C) 2001, 2002, 2003, 2004 The Mir-coders group
+ *
+ * This file is part of Mir.
+ *
+ * Mir is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * Mir 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 for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with Mir; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ *
+ * In addition, as a special exception, The Mir-coders gives permission to link
+ * the code of this program with  any library licensed under the Apache Software License,
+ * The Sun (tm) Java Advanced Imaging library (JAI), The Sun JIMI library
+ * (or with modified versions of the above that use the same license as the above),
+ * and distribute linked combinations including the two.  You must obey the
+ * GNU General Public License in all respects for all of the code used other than
+ * the above mentioned libraries.  If you modify this file, you may extend this
+ * exception to your version of the file, but you are not obligated to do so.
+ * If you do not wish to do so, delete this exception statement from your version.
+ */
+package org.codecoop.mir.core.dao.hibernate;
+
+import java.io.Serializable;
+import java.math.BigDecimal;
+import java.sql.Timestamp;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.List;
+
+import net.sf.hibernate.Criteria;
+import net.sf.hibernate.HibernateException;
+import net.sf.hibernate.Query;
+import net.sf.hibernate.Session;
+import net.sf.hibernate.SessionFactory;
+import net.sf.hibernate.Transaction;
+import net.sf.hibernate.expression.Criterion;
+import net.sf.hibernate.expression.Example;
+import net.sf.hibernate.expression.Expression;
+import net.sf.hibernate.expression.Order;
+
+import org.codecoop.mir.core.dao.DatabaseFailure;
+import org.codecoop.mir.core.dao.IDAO;
+import org.codecoop.mir.core.dao.IQueryCriteria;
+
+/**
+ * AbstractDAO
+ * @author idefix
+ * @version $Id: AbstractDAO.java,v 1.1 2004/11/06 16:20:48 idfx Exp $
+ */
+public abstract class AbstractDAO implements IDAO {
+  
+  private static SessionFactory sessionFactory;
+
+  /**
+   * Return the specific Object class that will be used for class-specific
+   * implementation of this DAO.
+   * @return the reference Class
+   * 
+   */
+  protected abstract Class getReferenceClass();
+
+  /**
+   * Execute a query. 
+   * @param query a query expressed in Hibernate's query language
+   * @return a distinct list of instances (or arrays of instances)
+   */
+  public List find(String query) throws DatabaseFailure {
+    System.out.println(query);
+    try {
+      List list = find(query, HibernateSessionManager.getSession());
+      for (Iterator iter = list.iterator(); iter.hasNext();) {
+        initializeCollections(iter.next());
+      }
+      return list;
+    } catch (HibernateException e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+  
+  protected List find(Criteria c) throws DatabaseFailure {
+    try {
+      List returnList;
+      returnList = c.list();    
+      for (Iterator iter = returnList.iterator(); iter.hasNext();) {
+        initializeCollections(iter.next());
+      }
+      return returnList;
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+  
+  public List find(int limit, int offset) throws DatabaseFailure {
+    return find(limit, offset, null, null);
+  }
+  
+  public List find(int limit, int offset, Object example) throws DatabaseFailure {
+    Example ex = Example.create(example);
+    ex.excludeZeroes();
+    ex.excludeNone();
+    ex.ignoreCase();
+    return find(limit, offset, ex, null);    
+  }
+  
+  protected List find(int limit, int offset, Criterion crit, Order order) 
+       throws DatabaseFailure {
+    try {
+      Session s = HibernateSessionManager.getSession();
+      Criteria c = s.createCriteria(getReferenceClass());
+      if(crit != null){
+        c.add(crit);  
+      }
+      if(order != null){
+        c.addOrder(order);  
+      }
+      c.setFirstResult(offset);
+      c.setMaxResults(limit);
+      return find(c);
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+  
+  /**
+   * @see org.codecoop.mir.core.dao.IArticleDAO#findById(java.lang.Integer)
+   */
+  protected Object findById(Integer id) throws DatabaseFailure{
+    try {
+      Session s = HibernateSessionManager.getSession();
+      Criteria c = s.createCriteria(getReferenceClass());
+      c.add(Expression.eq("id", id));
+      return find(c).get(0);
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Perform a find but use the session given instead of creating a new one.
+   * @param query a query expressed in Hibernate's query language
+   * @s the Session to use
+   */
+  protected List find(String query, Session s) throws HibernateException {
+    return s.find(query);
+  }
+
+  /**
+   * Return all objects related to the implementation of this DAO with no filter.
+   */
+  public List findAll() throws DatabaseFailure {
+    try {
+      return findAll(HibernateSessionManager.getSession());
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Return all objects related to the implementation of this DAO with no filter.
+   * Use the session given.
+   * @param s the Session
+   */
+  protected List findAll(Session s) throws DatabaseFailure {
+    try {
+      Criteria crit = s.createCriteria(getReferenceClass());
+      return find(crit);
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+  
+  
+
+  public List find(IQueryCriteria criteria) throws DatabaseFailure {
+    if(criteria instanceof QueryCriteria){
+      QueryCriteria c = (QueryCriteria)criteria;
+      return find(c.criteria());
+    }
+    throw new DatabaseFailure("No applicable implementation of IQueryCriteria");
+  }
+  
+  /**
+   * Obtain an instance of Query for a named query string defined in the mapping file.
+   * @param name the name of a query defined externally 
+   * @return Query
+   */
+  protected List getNamedQuery(String name) throws DatabaseFailure {
+    try {
+      return getNamedQuery(name, HibernateSessionManager.getSession());
+    } catch (Exception e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Obtain an instance of Query for a named query string defined in the mapping file.
+   * Use the session given.
+   * @param name the name of a query defined externally 
+   * @param s the Session
+   * @return Query
+   */
+  protected List getNamedQuery(String name, Session s) throws HibernateException {
+    Query q = s.getNamedQuery(name);
+    return q.list();
+  }
+
+  /**
+   * Obtain an instance of Query for a named query string defined in the mapping file.
+   * Use the parameters given.
+   * @param name the name of a query defined externally 
+   * @param params the parameter array
+   * @return Query
+   */
+  protected List getNamedQuery(String name, Serializable[] params)
+    throws DatabaseFailure {
+    try {
+      return getNamedQuery(name, params, HibernateSessionManager.getSession());
+    } catch (Exception e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Obtain an instance of Query for a named query string defined in the mapping file.
+   * Use the parameters given and the Session given.
+   * @param name the name of a query defined externally 
+   * @param params the parameter array
+   * @s the Session
+   * @return Query
+   */
+  protected List getNamedQuery(String name, Serializable[] params, Session s)
+    throws HibernateException {
+    Query q = s.getNamedQuery(name);
+    for (int i = 0; i < params.length; i++) {
+      setParameterValue(q, i, params[i]);
+    }
+    return q.list();
+  }
+
+  /**
+   * Convenience method to set paramers in the query given based on the actual object type in passed in as the value.
+   * You may need to add more functionaly to this as desired (or not use this at all).
+   * @param query the Query to set
+   * @param position the ordinal position of the current parameter within the query
+   * @param value the object to set as the parameter
+   */
+  protected void setParameterValue(Query query, int position, Object value) {
+    if (null == value) {
+      return;
+    } else if (value instanceof Boolean) {
+      query.setBoolean(position, ((Boolean) value).booleanValue());
+    } else if (value instanceof String) {
+      query.setString(position, (String) value);
+    } else if (value instanceof Integer) {
+      query.setInteger(position, ((Integer) value).intValue());
+    } else if (value instanceof Long) {
+      query.setLong(position, ((Long) value).longValue());
+    } else if (value instanceof Float) {
+      query.setFloat(position, ((Float) value).floatValue());
+    } else if (value instanceof Double) {
+      query.setDouble(position, ((Double) value).doubleValue());
+    } else if (value instanceof BigDecimal) {
+      query.setBigDecimal(position, (BigDecimal) value);
+    } else if (value instanceof Byte) {
+      query.setByte(position, ((Byte) value).byteValue());
+    } else if (value instanceof Calendar) {
+      query.setCalendar(position, (Calendar) value);
+    } else if (value instanceof Character) {
+      query.setCharacter(position, ((Character) value).charValue());
+    } else if (value instanceof Timestamp) {
+      query.setTimestamp(position, (Timestamp) value);
+    } else if (value instanceof Date) {
+      query.setDate(position, (Date) value);
+    } else if (value instanceof Short) {
+      query.setShort(position, ((Short) value).shortValue());
+    }
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Load object matching the given key and return it.
+   */
+  protected Object load(Class refClass, Serializable key) throws DatabaseFailure {
+    try {
+      return load(refClass, key, HibernateSessionManager.getSession());
+    } catch (Exception e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Load object matching the given key and return it.
+   */
+  protected Object load(Class refClass, Serializable key, Session s) 
+    throws DatabaseFailure {
+    try {
+      return s.load(refClass, key);
+    } catch (HibernateException e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Persist the given transient instance, first assigning a generated identifier. 
+   * (Or using the current value of the identifier property if the assigned generator is used.) 
+   */
+  public Serializable save(Object obj) throws DatabaseFailure {
+    try {
+      return save(obj, HibernateSessionManager.getSession());
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Persist the given transient instance, first assigning a generated identifier. 
+   * (Or using the current value of the identifier property if the assigned generator is used.) 
+   */
+  protected Serializable save(Object obj, Session s) throws HibernateException {
+    Serializable key = null;
+    Transaction transaction = s.beginTransaction();
+    try {
+      key = s.save(obj);
+      transaction.commit();
+    } catch (HibernateException e) {
+      if(transaction != null){
+        transaction.rollback();
+      }
+    }
+    return key;
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Either save() or update() the given instance, depending upon the value of its
+   * identifier property.
+   */
+  public void saveOrUpdate(Object obj) throws DatabaseFailure {
+    saveOrUpdate(obj, HibernateSessionManager.getSession());
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Either save() or update() the given instance, depending upon the value of its
+   * identifier property.
+   */
+  protected void saveOrUpdate(Object obj, Session s) throws DatabaseFailure {
+    try {
+      s.saveOrUpdate(obj);
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
+   * instance with the same identifier in the current session.
+   * @param obj a transient instance containing updated state
+   * @throws 
+   */
+  public void update(Object obj) throws DatabaseFailure {
+    try {
+      update(obj, HibernateSessionManager.getSession());
+    } catch (Throwable e) {
+      throw new DatabaseFailure(e);
+    } 
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Update the persistent state associated with the given identifier. An exception is thrown if there is a persistent
+   * instance with the same identifier in the current session.
+   * @param obj a transient instance containing updated state
+   * @param s the Session
+   */
+  protected void update(Object obj, Session s) throws DatabaseFailure {
+    try {
+      s.update(obj);
+    } catch (HibernateException e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
+   * Session or a transient instance with an identifier associated with existing persistent state. 
+   */
+  public void delete(Object obj) throws DatabaseFailure {
+    delete(obj, HibernateSessionManager.getSession());
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Remove a persistent instance from the datastore. The argument may be an instance associated with the receiving
+   * Session or a transient instance with an identifier associated with existing persistent state. 
+   */
+  protected void delete(Object obj, Session s) throws DatabaseFailure {
+    try {
+      s.delete(obj);
+    } catch (HibernateException e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+
+  /**
+   * Used by the base DAO classes but here for your modification
+   * Re-read the state of the given instance from the underlying database. It is inadvisable to use this to implement
+   * long-running sessions that span many business tasks. This method is, however, useful in certain special circumstances.
+   */
+  protected void refresh(Object obj, Session s) throws DatabaseFailure {
+    try {
+      s.refresh(obj);
+    } catch (HibernateException e) {
+      throw new DatabaseFailure(e);
+    }
+  }
+  
+  protected abstract void initializeCollections(Object o) throws DatabaseFailure;
+}