打开会话的Hibernate异常。我该怎么调试呢?

时间:2011-11-27 21:28:46

标签: java mysql hibernate java-ee transactions

我是hybernate的新手,我正在努力解决以下异常:

  

线程“AWT-EventQueue-0”中的异常   org.hibernate.HibernateException:非法尝试关联a   代理有两个开放的会话

当我尝试删除对象(订单)时,我得到了这个。

我的设置/代码:

Order.hbm.xml

<hibernate-mapping>
    <class name="com.database.entities.Order" table="ORDERS">
        <id name="orderId" type="java.lang.Long">
            <column name="ORDERID" />
            <generator class="identity" />
        </id>
         <property name="product" type="java.lang.String">
            <column name="SHIP" />
        </property>
        <property name="orderDate" type="java.util.Date">
            <column name="ORDERDATE" />
        </property>        
        <property name="quantity" type="java.lang.Integer">
            <column name="QUANTITY" />
        </property>       
        <many-to-one name="customer" class="com.database.entities.Customer" fetch="join">
            <column name="CUSTOMERID"/>
        </many-to-one>
        <many-to-one name="associate" column="ASSOCIATEID" class="com.database.entities.Employee" fetch="join">            
        </many-to-one>
    </class>
</hibernate-mapping>

会议持有人:

public class DBSession {


    private static SessionFactory sessionFactory;

    static{     
        Configuration cfg = new Configuration();        
        sessionFactory = cfg.configure().buildSessionFactory();     
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;      
    }

    public static void shutdown() {
        getSessionFactory().close();        
    }       



}

相关的DAO都扩展了以下内容:

public abstract class GenericDAO<T, ID extends Serializable> implements GenericDAOIF<T, ID> {

    private Class<T> persistentClass;
    private Session session;



    public Session getSession() {
        if(session == null || !session.isOpen()){
            session = DBUtil.getSessionFactory().openSession();
        }

        return session;
    }

    public void setSession(Session session) {
        this.session = session;
    }



    @SuppressWarnings("unchecked")
    @Override
    public T findById(ID id, boolean lock) {

        T entity;

        if(lock)
            entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
        else
            entity = (T) getSession().load(getPersistentClass(), id);

        return entity;
    }



    @Override
    public T makePersistent(T entity) {
        getSession().beginTransaction();
        getSession().saveOrUpdate(entity);
        flush();
        getSession().getTransaction().commit();
        return entity;
    }

    @Override
    public void flush() {
        getSession().flush();

    }

    @Override
    public void clear() {
        getSession().clear();

    }

    @Override
    public void makeTransient(T entity) {
        getSession().getTransaction().begin();
        getSession().delete(entity);
        getSession().getTransaction().commit();


    }


}

当我尝试删除订单时,所有其他查询都有效(例如插入/选择其他实体和订单)我在GenericDAO代码的以下部分中得到以下异常:

public void makeTransient(T entity) {
    getSession().getTransaction().begin();
    getSession().delete(entity);//--> Exception here
    getSession().getTransaction().commit();


}

异常堆栈跟踪:

Exception in thread "AWT-EventQueue-0" org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions
    at org.hibernate.proxy.AbstractLazyInitializer.setSession(AbstractLazyInitializer.java:126)
    at org.hibernate.engine.StatefulPersistenceContext.reassociateProxy(StatefulPersistenceContext.java:573)
    at org.hibernate.engine.StatefulPersistenceContext.unproxyAndReassociate(StatefulPersistenceContext.java:618)
    at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:89)
    at org.hibernate.event.def.DefaultDeleteEventListener.onDelete(DefaultDeleteEventListener.java:73)
    at org.hibernate.impl.SessionImpl.fireDelete(SessionImpl.java:956)
    at org.hibernate.impl.SessionImpl.delete(SessionImpl.java:934)
    at com.dao.GenericDAO.makeTransient(GenericDAO.java:100)
    at com.ui.panels.AdminDBPanel$11.actionPerformed(AdminDBPanel.java:414)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)

只有当我删除订单时才会发生这种情况(这就是我只发布了部分代码的原因)。

我不明白这个例外是什么意思 但是搜索Google我尝试了以下工作:

@Override
public void makeTransient(T entity) {
        getSession().merge(entity);  
    getSession().getTransaction().begin();
    getSession().delete(entity);
    getSession().getTransaction().commit();


}

2)关闭会话并重新打开它:

public Session getSession() {
    if(session == null || !session.isOpen()){
        session = DBUtil.getSessionFactory().openSession();
    }
            else{
                 session.close();
                 session = DBUtil.getSessionFactory().openSession();
            }

    return session;
}

我被困在如何调试这个。

非常欢迎任何意见

更新:

额外信息:
员工映射:

<hibernate-mapping>
    <class name="com.database.entities.Employee" table="ASSOCIATE">
        <id name="assosiateId" type="java.lang.Long">
            <column name="ASSOCIATEID" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="java.lang.String" not-null="true">
            <column name="FIRSTNAME" />
        </property>
        <property name="lastName" type="java.lang.String" not-null="true">
            <column name="LASTNAME" />
        </property>
        <property name="userName" type="java.lang.String" not-null="true">
            <column name="USERNAME" />
        </property>
        <property name="password" type="java.lang.String" not-null="true">
            <column name="PASSWORD" />
        </property>
        <set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true">
            <key>
                <column name="ASSOCIATEID" />
            </key>
            <one-to-many class="com.database.entities.Order" />
        </set>
    </class>
</hibernate-mapping>

<hibernate-mapping>
    <class name="com.database.entities.Customer" table="CUSTOMER">
        <id name="customerId" type="java.lang.Long">
            <column name="CUSTOMERID" />
            <generator class="identity" />
        </id>
        <property name="customerName" type="java.lang.String">
            <column name="CUSTOMERNAME" />
        </property>
        <set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true">
            <key>
                <column name="CUSTOMERID" />
            </key>
            <one-to-many class="com.database.entities.Order" />
        </set>
    </class>
</hibernate-mapping>  

客户映射:

<hibernate-mapping>
    <class name="com.database.entities.Customer" table="CUSTOMER">
        <id name="customerId" type="java.lang.Long">
            <column name="CUSTOMERID" />
            <generator class="identity" />
        </id>
        <property name="customerName" type="java.lang.String">
            <column name="CUSTOMERNAME" />
        </property>
        <set name="orders" table="ORDERS" inverse="true" cascade="all" lazy="true">
            <key>
                <column name="CUSTOMERID" />
            </key>
            <one-to-many class="com.database.entities.Order" />
        </set>
    </class>
</hibernate-mapping>

OrderDAO:

public class OrderDAO extends GenericDAO<Order, Long> implements OrderDAOIF {

    @Override
    public void addOrder(Order order, Customer customer, Associate associate) {
        Session session = getSession();
        Transaction tx = session.beginTransaction();
        order.setAssociate(associate);
        order.setCustomer(customer);

        session.saveOrUpdate(order);

        tx.commit();
        session.close();        
    }

    @Override
    public void updateOrderStatus(String status, Long orderId) {

        Order order = findById(orderId, false);
        order.setOrderState(status);
        Session session = getSession();
        Transaction tx = session.beginTransaction();
        session.saveOrUpdate(order);
        tx.commit();
        session.close();


    }


}

启动异常的代码:

Order order = getFactory().getOrderDAO().findById(Long.valueOf(orderId), false);
getFactory().getOrderDAO().makeTransient(order);//--> Exception thrown here

1 个答案:

答案 0 :(得分:7)

错误表示您尝试将一个会话中加载的对象与另一个会话相关联。你如何进行会话管理存在一个更大的问题 - 但如果没有更多的信息,我无法对此发表评论。您尝试的合并工作可以通过简单的更改来修复问题 - 使用merge方法返回的引用进行进一步操作。

@Override
public void makeTransient(T entity) {
    T newEntityRef =    getSession().merge(entity);  
    getSession().getTransaction().begin();
    getSession().delete(newEntityRef);
    getSession().getTransaction().commit();
}

问题是由于这段代码造成的。

Order order = getFactory().getOrderDAO().findById(Long.valueOf(orderId), false);
getFactory().getOrderDAO().makeTransient(order);//--> Exception thrown here

假设getOrderDao()正在创建OrderDao类的新实例。对findById的调用使用一个新的session实例(让我们称之为s1)来加载该对象。加载的对象是与用于加载它的会话相关联的代理。然后下一次调用创建一个新的OrderDAO(通过调用getOrderDAO方法) - 现在当makeTransient被调用时,创建一个新会话(让我们称之为s2)。您现在正尝试将由s1加载的代理传递给s2 - 这是异常所指示的内容。 Merge方法获取对象,并在s2中创建新对象或将内容与现有对象合并 - 输入对象传递的方式不会更改 - 创建的新对象将是返回值。

以这种方式编写代码也可以在没有合并的情况下解决问题。

OrderDao orderDao = getFactory().getOrderDAO();
Order order = orderDao.findById(Long.valueOf(orderId), false);
orderDao.makeTransient(order);

上述代码的另一个问题是会话未关闭。每个会话都使用JDBC连接 - 因此会导致连接泄漏。

请查看以下内容,了解如何修复代码。基本上,您的DAO不应该打开新会话,也不应该管理事务。你应该在外面做。

http://community.jboss.org/wiki/SessionsAndTransactions

http://community.jboss.org/wiki/GenericDataAccessObjects