Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate exception on open sessions. How can I debug this?

I am newbie in hybernate and I am struggling with the following exception:

Exception in thread "AWT-EventQueue-0" org.hibernate.HibernateException: illegally attempted to associate a proxy with two open Sessions

I get this when I try to delete an object (an order).

My setting/code:

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>

A session holder:

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();        
    }       



}

And relevant DAOs all extending the following:

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();


    }


}

While all the other queries work (e.g. insert/select for other entities and order) when I try to delete an order I get the following exception in the following part of the code of GenericDAO:

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


}

The exception stack trace:

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)

This happens only when I delete an order (that is why I posted only that part of code).

I do not understand what this exception means.
But searching Google I tried the following which did not work:
1) Merging with session:

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


}

2) Closing the session and reopening it:

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

    return session;
}

I am stuck on how to debug this.

Any input is highly welcome

UPDATE:

Extra info:
Employee mapping:

<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>  

Customer 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();


    }


}

The code that starts the exception:

Order order = getFactory().getOrderDAO().findById(Long.valueOf(orderId), false);
getFactory().getOrderDAO().makeTransient(order);//--> Exception thrown here
like image 660
Cratylus Avatar asked Nov 27 '11 21:11

Cratylus


1 Answers

The error means that you are trying to associate a object loaded in one session with another session. There is a bigger issue with how you are doing session management - but I cannot comment on that without a lot more info. The merge work around you tried can fix the problem with a simple change - use the reference returned by the merge method for further operation.

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

The problem is due to this piece of code.

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

Assuming that the getOrderDao() is creating a new instance of the the OrderDao class. The call to findById uses a new instance of session (let us call it s1) to load the object. The loaded object is a proxy which is associated with the session that was used to load it. Then next call creates a new OrderDAO (by calling getOrderDAO method) - now when makeTransient is called a new session (let us call this s2) is created. You are now trying to pass a proxy loaded by s1 to s2 - which is what the exception is indicating. Merge method takes the object and either creates a new object in s2 or merges content with an existing object - either ways the input object passed is not changed - the new object that is created will be the return value.

Writing the code this way will also fix the issue without the merge.

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

The other problem with the above code is that the session is not getting closed. Each session uses a JDBC connection - so it will lead to a connection leak.

Take a look at the following to get an idea of how to fix your code. Basically your DAO should not open a new session and should not be managing transactions. You should be doing it outside.

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

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

like image 79
gkamal Avatar answered Sep 29 '22 04:09

gkamal