简体   繁体   中英

Can we use JPA outsite EJB container?

My application is running on Jboss 4.0.5 GA and need to be upgraded to run on jboss 7.1.1 final. Everything in JSF pages, business logic are solved. But the critical thing we're facing: In old application in jboss4 we do not use JPA, we use hibernate session directly. And manage hibernate session by threadlocal. We applied 3 tiers application: [UI backend bean] call [EJB to execute business] call [DAO objects to get and update database by hibernate session].
This design is broken, NOW! Because we cannnot find the way to manage entity manager in threadlocal like hibernate session. May be I'm bad developer.
Please help me, can we use jpa outsite EJB. I would like a static class with name DAOUtil to manage and get entity manager, also perform save or update data. Anyone tell me the way to do this. How about datasource(xa-datasource), how about persistent.xml?
This is class to access to databse:

package com.esilicon.dao.hibernate;

import java.io.Serializable;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
import org.hibernate.engine.spi.SessionImplementor;

public class HibernateDAOSession extends DAOSession {


    /**
     * @associates Class
     */
    private static HashMap implementations = new HashMap();
    private Session hibernateSession;
    // private Transaction tx;
    private boolean JTAEnvironment;
    private EntityManager em;

    public HibernateDAOSession(Session s, boolean jta) {
        this.hibernateSession = s;
        this.JTAEnvironment = false;
    }

    public HibernateDAOSession(Session s, boolean jta, EntityManager em) {
        this.hibernateSession = s;
        this.JTAEnvironment = false;
        this.em = em;
    }

    public BaseDAO getDAO(Class clazz) {
        try {
            Class impl = getImplementationClass(clazz);
            HibernateDAO dao = (HibernateDAO) impl.newInstance();
            // dao.setCurrentSession(this.getHibernateSession());
            // session will be provided by DAOUtil from a threadlocal variable.
            return dao;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private Class getImplementationClass(Class clazz) throws ClassNotFoundException {
        Class impl = (Class) implementations.get(clazz);
        if (impl == null) {
            String name = clazz.getName();
            String packageName = clazz.getPackage().getName();
            String className = name.substring(packageName.length() + 1);
            StringBuffer implClassName = new StringBuffer(packageName).append(".hibernate.").append(className).append("DAO");
            impl = Class.forName(implClassName.toString());
            implementations.put(clazz, impl);
        }
        return impl;
    }

    public void close() {
        if (this.JTAEnvironment)
            return;
        try {
            Session s = this.getHibernateSession();
            if (s != null && s.isOpen() && this.getEm() != null) {
                s.close();
                this.setHibernateSession(null);
                /*
                 * this.getEm().clear(); this.getEm().close();
                 */
                this.setEm(null);
            }

            /*if (s != null && s.isOpen()) {

            }*/

        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }

    }

    public void beginTransaction() {
        try {
            /*if (getHibernateSession().getTransaction() == null) {
                this.getHibernateSession().beginTransaction();
            } else if (!getHibernateSession().getTransaction().isActive() || getHibernateSession().getTransaction().wasCommitted()) {
                getHibernateSession().getTransaction().begin();
            }*/
            //return getHibernateSession().getTransaction();
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public void commit() {
        //this.getHibernateSession().flush();
        /*if (this.JTAEnvironment)
            return;
        try {
            if (getHibernateSession().getTransaction() != null && getHibernateSession().getTransaction().isActive()) {
                getHibernateSession().getTransaction().commit();
            }
        } catch (HibernateException e) {
            e.printStackTrace();
            rollback();
            throw new HibernateDAOException(e);
        }*/
    }

    public void rollback() {
        // TODO: should we allow rolback on session in JTAEnvironment ?
        /*try {
            if (getHibernateSession().getTransaction() != null && getHibernateSession().getTransaction().isActive()) {
                getHibernateSession().getTransaction().rollback();
            }
        } finally {
            // close();
            DAOUtil.closeEntityManager();
        }*/
    }

    public Transaction getCurrentTransaction() {
        return getHibernateSession().getTransaction();
    }

    private Query prepareQuery(Query q, int start, int count, Map params) {
        String[] namedParams = q.getNamedParameters();
        if (namedParams.length > 0 && params != null) {
            for (int i = 0; i < namedParams.length; i++) {
                if (params.get(namedParams[i]) instanceof java.util.List) {
                    q.setParameterList(namedParams[i], (List) params.get(namedParams[i]));
                } else {
                    q.setParameter(namedParams[i], params.get(namedParams[i]));
                }
            }
        }
        if (start >= 0)
            q.setFirstResult(start);
        if (count >= 0)
            q.setMaxResults(count);
        return q;
    }

    public Session getHibernateSession() {
        return hibernateSession;
    }

    public void setHibernateSession(Session hibernateSession) {
        this.hibernateSession = hibernateSession;
    }

    public Object update(Object o) {
        try {
            this.getHibernateSession().update(o);
            return o;
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }

    }

    public boolean isJTAEnvironment() {
        return JTAEnvironment;
    }

    public Object save(Object o) {
        try {
            this.getHibernateSession().save(o);
            return o;
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public Object saveOrUpdate(Object o) {
        try {
            this.getHibernateSession().saveOrUpdate(o);
            return o;
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }

    }

    public void flush() {
        try {
            this.getHibernateSession().flush();
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public Object refresh(Object o) {
        try {
            this.getHibernateSession().refresh(o);
            return o;
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public void evict(Object o) {
        try {
            this.getHibernateSession().evict(o);
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public Object query(String query, Map map, boolean uniqueResult) {
        try {
            Query q = this.getHibernateSession().createQuery(query);
            prepareParameters(q, map);
            if (uniqueResult) {
                return q.uniqueResult();
            } else {
                return q.list();
            }
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    private void prepareParameters(Query q, Map map) {
        if (map == null)
            return;
        String[] params = q.getNamedParameters();
        for (int i = 0; i < params.length; i++) {
            if (map.get(params[i]) instanceof java.util.List) {
                q.setParameterList(params[i], (List) map.get(params[i]));
            } else {
                q.setParameter(params[i], map.get(params[i]));
            }
        }
    }

    public Connection getConnection() {
        SessionImplementor si = (SessionImplementor) getHibernateSession();
        //this.connection = si.connection();
        return si.connection();
    }

    public void delete(Object o) {
        try {
            this.getHibernateSession().delete(o);
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }

    }

    public Object findUniqueEntityByID(Class entityClass, Serializable id) {
        try {
            return this.getHibernateSession().get(entityClass, id);
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public int executeUpdate(String query, Map params) {
        try {
            Query q = this.getHibernateSession().createQuery(query);
            prepareParameters(q, params);
            return q.executeUpdate();
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public Object nativeQuery(String query, Map map, boolean uniqueResult) {
        try {
            Query q = this.getHibernateSession().createSQLQuery(query);
            prepareParameters(q, map);
            if (uniqueResult) {
                return q.uniqueResult();
            } else {
                return q.list();
            }
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public int executeNativeUpdate(String query, Map params) {
        try {
            Query q = this.getHibernateSession().createSQLQuery(query);
            prepareParameters(q, params);
            return q.executeUpdate();
        } catch (HibernateException e) {
            e.printStackTrace();
            throw new HibernateDAOException(e);
        }
    }

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    @Override
    public Query createQuery(String hqlQuery) {
        return getHibernateSession().createQuery(hqlQuery);
    }

    @Override
    public SQLQuery createSQLQuery(String nativeQuery) {
        // TODO Auto-generated method stub
        return getHibernateSession().createSQLQuery(nativeQuery);
    }

    @Override
    public void disconnect() {
        // TODO Auto-generated method stub
        getHibernateSession().disconnect();
    }

    @Override
    public Object get(Class<?> clazz, Serializable id) {
        // TODO Auto-generated method stub
        return getHibernateSession().get(clazz, id);
    }

    @Override
    public Object load(Class<?> clazz, Serializable id) {
        // TODO Auto-generated method stub
        return getHibernateSession().load(clazz, id);
    }

    @Override
    public Object merge(Object o) {
        // TODO Auto-generated method stub
        return getHibernateSession().merge(o);
    }

    @Override
    public Query getNamedQuery(String nameQuery) {
        // TODO Auto-generated method stub
        return getHibernateSession().getNamedQuery(nameQuery);
    }
}

Class to manage HibernateSessionDAO

package com.esilicon.dao;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.hibernate.Session;
import org.hibernate.proxy.HibernateProxy;

import com.esilicon.dao.hibernate.HibernateDAOSession;
import com.esilicon.util.logging.Logger;

public class DAOUtil {
    public static final String PERSISTENT_UNIT = "vms4_jboss7";

    static ThreadLocal<DAOSession> threadLocalDAOEntityManager = new ThreadLocal<DAOSession>();
    static Logger logger = Logger.getLogger(DAOUtil.class.getName());

    public static DAOSession openEntityManager(DAOEntityManagerFactory factory) {
        DAOSession entityManager = (DAOSession) threadLocalDAOEntityManager.get();
        if (entityManager != null && entityManager.isOpen()) {
            return entityManager;
        }
        try {
            entityManager = factory.getEntityManager();
        } catch (Exception e) {
            // e.printStackTrace();
            entityManager = factory.openEntityManager();
        }
        threadLocalDAOEntityManager.set(entityManager);
        return entityManager;
    }

    public static DAOSession openSession(DAOSessionFactory factory) {

        DAOSession daoSession = (DAOSession) threadLocalDAOEntityManager.get();
        if (daoSession != null && daoSession.isOpen()) {
            return daoSession;
        }
        try {
            threadLocalDAOEntityManager.remove();
            daoSession = factory.getSession();
        } catch (Exception e) {
            e.printStackTrace();
            daoSession = factory.openSession();
        }
        threadLocalDAOEntityManager.set(daoSession);
        return daoSession;
    }

    public static DAOSession openSession(DAOEntityManagerFactory factory) {

        return openEntityManager(factory);
    }

    public static DAOSession getEntityManager() {
        DAOSession entityManager = (DAOSession) threadLocalDAOEntityManager.get();
        if (entityManager == null || !entityManager.isOpen()) {
            entityManager = DAOUtil.openEntityManager(DAOEntityManagerFactory.getInstance(null));
        }
        return entityManager;
    }

    public static DAOSession getSession() {
        return getEntityManager();
    }

    public static void closeEntityManager() {
        DAOSession entityManager = (DAOSession) threadLocalDAOEntityManager.get();
        if (entityManager != null) {
            entityManager.close();
            logger.debug("EntityManager Closed for Thread " + Thread.currentThread().getName());
            threadLocalDAOEntityManager.remove();
        }
    }

    public static void closeSession() {
        closeEntityManager();
    }

    public static void beginTransaction() {
        DAOSession entityManager = (DAOSession) threadLocalDAOEntityManager.get();
        logger.debug("--- BeginTransaction --- Thread " + Thread.currentThread().getName());
        if (entityManager == null) {
            entityManager = openEntityManager(DAOEntityManagerFactory.getInstance(null));
        }
        entityManager.beginTransaction();
    }

    public static void commitTransaction() {
        DAOSession entityManager = (DAOSession) threadLocalDAOEntityManager.get();
        logger.debug("--- CommitTransaction --- Thread " + Thread.currentThread().getName());
        entityManager.commit();
    }

    public static void rollbackTransaction() {
        DAOSession entityManager = (DAOSession) threadLocalDAOEntityManager.get();
        if (entityManager != null && entityManager.isOpen()) {
            entityManager.rollback();
        }
    }

    public static BaseDAO getDAO(Class clazz) {
        return getEntityManager().getDAO(clazz);
    }

    public static Object narrow(Object proxy) {

        try {
            return ((HibernateProxy) proxy).getHibernateLazyInitializer().getImplementation();
        } catch (Exception e) {
            return proxy; // not a proxy
        }

    }

    public static void closeConnection(Connection con) {
        try {
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static Connection getNonXAConnection() {
        try {
            InitialContext context = new InitialContext();
            DataSource dataSource = (DataSource) context.lookup(JNDILookup.PURE_CONNECTION_JNDI);
            return dataSource.getConnection();
        } catch (Exception e) {
            e.printStackTrace();
            logger.fatal(e.getMessage(), e.getCause());
        }
        return null;
    }
}

Use dependency injection to inject the entity manager into your dao classes:

For example:

@PersistenceContext
private EntityManager entityManager;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM