These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: my DAO is broken, anyone have one that works?
PostPosted: Sat Aug 19, 2006 8:13 pm 
Beginner
Beginner

Joined: Sat Aug 19, 2006 8:04 pm
Posts: 30
hi, i'm using hibernate and it is one of the best things ever. the other guys at work spend so much time dealing with databases, i don't even think about it much at all.

anyways, i'm having some problems with my DAO. specifically, i'm getting non-unique object, transient object, session is closed, (among others) exceptions pretty much at random.

i bought the book hibernate quickly, i'm using what i got from there (pretty much) in a webapp. i'm wondering if someone can either tell me what i'm doing wrong, or better yet just post up a DAO that they've been using that doesn't cause exceptions.

what about using spring to handle all this? really i'm kind of upset i have to write and maintain this code, it would be nice if hibernate did all this for me, and just gave me a simple API, saveUpdate(), delete(), read(), readAll(). i think something like that would be very sensible, i'm not sure why the burden of handling sessions and all this crap below is forced on the user.

here's my broke ass DAO

Code:
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.Query;
import java.io.Serializable;

import java.util.List;

/**
* A layer supertype that handles the common operations for all Data Access Objects.
*/
public class DAO<T, PK extends Serializable> implements GenericDAO<T, PK> {

        private Session session;
        private Transaction tx;
        private Class<T> type;

        public DAO(Class<T> type) {
                this.type = type;
        }

        @SuppressWarnings("unchecked")
        public PK create(T o) {
                Serializable pk = null;
                try {
                        startOperation();
                        pk = session.save(o);
                        tx.commit();
                } catch (HibernateException e) {
                        handleException(e);
                }
                return (PK)pk;
        }

        @SuppressWarnings("unchecked")
        public T read(PK id) {
                T o = null;
                try {
                        startOperation();
                        o = (T) session.load(type, id);
                        tx.commit();
                } catch (HibernateException e) {
                        handleException(e);
                }
                return o;
        }

        public void saveOrUpdate(T o)  {
                try {
                        startOperation();
        //              session.clear();
                        session.merge(o);
                        tx.commit();
                } catch (HibernateException e) {
                        handleException(e);
                }
        }

        public void update(T o) {
                try {
                        startOperation();
                //      session.clear();
                        session.update(o);
                        tx.commit();
                } catch (HibernateException e) {
                        handleException(e);
                }
        }

        public void delete(T o) {
                try {
                        startOperation();
                        session.delete(o);
                        tx.commit();
                } catch (HibernateException e) {
                        handleException(e);
                }
                ServiceLocator.closeSession();
        }

        @SuppressWarnings("unchecked")
        public List<T> readAll() {
                List<T> objects = null;
                try {
                        startOperation();
                        Query query = session.createQuery("from " + type.getName());
                        objects = query.list();
                        tx.commit();
                } catch (HibernateException e) {
                        handleException(e);
                }
                return objects;
        }

    public Query getQuery(String queryName) throws HibernateException  {
        session = ServiceLocator.getSession();
        return session.getNamedQuery(type.getSimpleName() + "." + queryName);
    }

        protected void handleException(HibernateException e)
                        throws DataAccessLayerException {
                ServiceLocator.rollback(tx);
                throw new DataAccessLayerException(e);
        }

        protected void startOperation() throws HibernateException {
                if (ServiceLocator.getFactory() == null)  {
                        ServiceLocator.buildFactory();
                }
                session = ServiceLocator.getSession();
                tx = session.beginTransaction();
        }
}


and here's the ServiceLocator class that uses the ThreadLocal to handle the session. one thing i'm not sure of is how / when to call session.close(); ... also i'm having a problem with cascading, but that's another thread.

Code:
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.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class ServiceLocator {

        private static final ThreadLocal<Session> t = new ThreadLocal<Session>();
        private static SessionFactory factory;
    private static Log log = LogFactory.getLog(ServiceLocator.class);

        static  {
                try  {
                        factory = new Configuration().configure().buildSessionFactory();
                } catch (HibernateException e)  {
                        e.printStackTrace();
                }
        }

        public static Session getSession()  throws HibernateException  {
                Session s = t.get();
                if (s == null)  {
                        s = factory.openSession();
                        t.set(s);
                }
                return s;
        }

        public static void closeSession() {
                Session s = t.get();
                if (s != null)  {
                        try  {
                                s.close();
                        } catch (HibernateException e)  {
                                e.printStackTrace();
                        }
                }
                t.set(null);
        }

   public static void rollback(Transaction tx) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (HibernateException ignored) {
            log.error("Couldn't rollback Transaction", ignored);
        }
    }

        public static SessionFactory getFactory() {
                return factory;
        }

        public static void buildFactory() {
                if (factory != null)  {
                        factory.close();
                }
                factory = new Configuration().configure().buildSessionFactory();
        }
}


any ideas? thanks, as soon as i get this figured out i'm gonna be cranking out the webapps in no time.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.