Illegal attempt to associate a collection with two open sessions

I'm trying to add a pojo to a collection in another pojo. I'm sure I'm making a really stupid mistake somewhere along the lines but I can't figure out how to solve it.

I have a pojo LookupTable which contains a list of Columns:

public class LookupTable {
  private long id;
  // More properties go here...
  private List<Column> columns;

  public void addColumn(Column column) {
    this.columns.add(column);
  }

  // More methods go here...
}

In my hibernate configuration I have:

<class name="LookupTable" table="ARR_LOOKUP_TABLE">
  <id name="id" column="ID">
    <generator class="native"/>
  </id>
  <!-- Some properties here -->
  <bag name="columns" cascade="all,delete-orphan" access="field">
    <key column="LOOKUP_TABLE" not-null="true"/>
    <one-to-many class="Column"/>
  </bag>
</class>

<class name="Column" table="ARR_LOOKUP_COLUMN">
  <id name="id" column="ID">
    <generator class="native"/>
  </id>
  <!-- Some properties here -->
</class>

In my Spring config file I have:

<tx:advice id="txAdvice" transaction-manager="txManager">
  <tx:attributes>
    <tx:method name="*" propagation="REQUIRED"/>
  </tx:attributes>
</tx:advice>
<aop:config>
  <aop:pointcut id="managers" expression="execution(public * com.foo.*Manager.*(..))"/>
  <aop:advisor advice-ref="txAdvice" pointcut-ref="managers"/>
</aop:config>

And finally the code where it all fails within my manager class (com.foo.LookupTableManager):

public void addColumnToTable(Column column, long tableId) {
  LookupTable lookupTable = this.lookupTableDao.findById(tableId);
  lookupTable.addColumn(column);
  this.lookupTableDao.saveOrUpdate(lookupTable);
}

The variable lookupTableDao here refers to a simple DAO class which extends HibernateDaoSupport.

The error I get is:

org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions
  at org.hibernate.collection.AbstractPersistentCollection.setCurrentSession(AbstractPersistentCollection.java:410)
  at org.hibernate.event.def.OnUpdateVisitor.processCollection(OnUpdateVisitor.java:43)
  at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:101)
  at org.hibernate.event.def.AbstractVisitor.processValue(AbstractVisitor.java:61)
  at org.hibernate.event.def.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:55)
  at org.hibernate.event.def.AbstractVisitor.process(AbstractVisitor.java:123)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:293)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
  at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
  at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
  at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
  at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:495)
  at com.foo.AbstractDao.saveOrUpdate(AbstractDao.java:29)
  at com.foo.LookupTableManager.addColumnToTable(LookupTableManager.java:338)
... etc ...

OK, I understand the basic message I'm getting. But what I don't understand is where I get the second session.... Can anyone help me with this?

I'm using Hibernate 3.2.6.ga, Spring 2.5.5 and Tomcat 6.0


Asked by: Walter449 | Posted: 21-01-2022






Answer 1

Turns out I didn't have a transaction at all. I used almost the same transaction configuration in one of my other config files.

The pointcut over there was also called "managers", so my advisor here was referencing the pointcut in the other file.

Renaming the pointcut solved my problem.

Answered by: Chelsea346 | Posted: 22-02-2022



Answer 2

My guess is that the lookupTableDao.findById call is getting your object in one session, but the lookupTableDao.saveOrUpdate is a different one - how do you get the Session object, via Spring?

Where is the Column object coming from - is that already on the DB or new?

Answered by: Walter146 | Posted: 22-02-2022



Answer 3

The problem was with the Open Session In view filter mapping. It was creating a session on getSession And other on save.

You can change only singleSession as false default its true

Answered by: William334 | Posted: 22-02-2022



Answer 4

Apparently using merge will probably fix the problem

myInstance = (myInstanceClass) Session.merge(myInstance);

Answered by: Freddie496 | Posted: 22-02-2022



Answer 5

I had the same problem with my following code: I wanted to update a certain entity Store. I was retrieving it from this method:

@Override
public Store getStoreByStoreId(final long storeId) {
    getHibernateTemplate().execute(new HibernateCallback<Store>() {
        @Override
        public StoredoInHibernate(Session session) throws HibernateException, SQLException {
            return (Store) session.createCriteria(Store.class)
                    .add(Restrictions.eq(Store.PROP_ID, storeId))
                    .uniqueResult();
        }
    });
}

Then, I was updating the store in the following method:

@Override
public void updateStoreByStoreId(final long storeId) {
    getHibernateTemplate().execute(new HibernateCallback<Void>() {
        @Override
        public Void doInHibernate(Session session) throws HibernateException, SQLException {
            Store toBeUpdated =  getStoreByStoreId(storeId);

            if (toBeUpdated != null){
                // ..change values for certain fields
                session.update(toBeUpdated);
            }
            return null;
        }
    });
} 

It turns out I got the "Illegal attempt ..." error because the first session from the get method was not closing, and I was trying to update with the other session the store. The solution for me was to move the call for retrieving the store to be updated in the update method.

@Override
public void updateStoreByStoreId(final long storeId) {
    getHibernateTemplate().execute(new HibernateCallback<Void>() {
        @Override
        public Void doInHibernate(Session session) throws HibernateException, SQLException {
            Store toBeUpdated =  (Store) session.createCriteria(Store.class)
                    .add(Restrictions.eq(Store.PROP_ID, storeId))
                    .uniqueResult();

            if (toBeUpdated != null){
                // ..change values for certain fields
                session.update(toBeUpdated );
            }
            return null;
        }
    });
} 

Answered by: Kimberly471 | Posted: 22-02-2022



Answer 6

If you only want a transaction over a part of your code you can use something like this:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

and in the class:

@Autowired private SessionFactory sessionFactory;

Later, around the code that should do things in the same transaction:

Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();

Stuff stuff = getStuff();
manipulate(stuff);
send(stuff);
save(stuff);

tx.commit();

I use this inside a loop in some long-running batch jobs.

Answered by: Lana749 | Posted: 22-02-2022



Answer 7

I was using windows server IIS and just changing the AppPool Managed Pipeline mode from Integrated to Classic solved my issue.

Thanks

Answered by: Maya541 | Posted: 22-02-2022



Similar questions

java - Spring: Illegal attempt to associate a collection with two open sessions, for M-to-M

My program has a user and a role configuration of security, two models that have between them a many-to-many relationship. When I am trying to save a new user and his m-to-m relationship in a separate table named "user_roles", I get the following error on the session.save() function: org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions. Collection : [com.session...


java - Illegal attempt to associate a collection with two open sessions in hibernate

I am using hibernate and spring and I am getting this exception upon executing the following code: Session oSession = getSession(); try { oSession.setFlushMode(FlushMode.COMMIT); getHibernateTemplate().delete(oProject); oSession.flush(); bResult = true; } catch (Exception e) { bResult = false; logger.error(e); }


java - Illegal attempt to associate a collection with two open session

I want to insert one transaction with multiple product as shown below in addTrasction method ,there are one to many relationship between transaction and product class ,but this error appears Illegal attempt to associate a collection with two open sessions this is hibernate cofigurtion File path2Config= new File("./src/com/config/hibernate.cfg.xml"); SessionFactory sessionfactory=new ...


java - How to associate data to the elements in a collection without modifying the elements?

usually, when I'm doing OpenGL programming, I have a Mesh class like this: public class Mesh { // General 3D stuff List&lt;Vector3f&gt; vertices = new ArrayList&lt;&gt;(); List&lt;Vector3f&gt; normals = new ArrayList&lt;&gt;(); List&lt;Vector2f&gt; texCoords = new ArrayList&lt;&gt;(); // OpenGL-specific stuff protected int vertices; protected boolean dirty; protected int ve...


java - Spring: Illegal attempt to associate a collection with two open sessions, for M-to-M

My program has a user and a role configuration of security, two models that have between them a many-to-many relationship. When I am trying to save a new user and his m-to-m relationship in a separate table named "user_roles", I get the following error on the session.save() function: org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions. Collection : [com.session...


garbage collection - Java Concurrent and Parallel GC

This article here suggests to use -XX:+UseParNewGC "To enable a parallel young generation GC with the concurrent GC". My confusion is that in order to enable both parallel and concurrent GC, should I use -XX:+UseParNewGC or use both -XX:+UseParNewGC and -XX:+Use...


java - Printing out items in any Collection in reverse order?

I have the following problem in my Data Structures and Problem Solving using Java book: Write a routine that uses the Collections API to print out the items in any Collection in reverse order. Do not use a ListIterator. I'm not putting it up here because I want somebody to do my homework, I just can't seem to understand exactly what it is asking for me to code! W...


java - How do I bind collection attributes to a form in Spring MVC

I'm trying to bind one of my model objects to the fields of a form, using Spring-MVC. Everything works fine, except that one of the attributes of the model object is an unordered collection. Doing something like &lt;c:forEach items="${m.items}" var="i" varStatus="itemsRow"&gt; &lt;form:input path="items[${itemsRow.index}]"/&gt; &lt;/c:forEach&gt; &lt;form:errors path="items" /&gt;


java - Best Collection To Use?


Does using final for variables in Java improve garbage collection?

Today my colleagues and me have a discussion about the usage of the final keyword in Java to improve the garbage collection. For example, if you write a method like: public Double doCalc(final Double value) { final Double maxWeight = 1000.0; final Double totalWeight = maxWeight * value; return totalWeight; } Declaring the variables in the method final


generics - Java: How to create a collection of a specific parent type and not its subtypes?

I am learning Java for a test (tomorrow) and am wondering about a question that will probably never come up but has got me curious. Is it possible to create a new collection class such as a list or something that can hold only a specific type and not its sub-types? Would I use generics to achieve this goal?


java - Can Hibernate return a collection of result objects OTHER than a List?

Does the Hibernate API support object result sets in the form of a collection other than a List? For example, I have process that runs hundreds of thousands of iterations in order to create some data for a client. This process uses records from a Value table (for example) in order to create this output for each iteration. With a List I would have to iterate through the entire list in order to find a certa...


java - JPA map collection of Enums

Is there a way in JPA to map a collection of Enums within the Entity class? Or the only solution is to wrap Enum with another domain class and use it to map the collection? @Entity public class Person { public enum InterestsEnum {Books, Sport, etc... } //@??? Collection&lt;InterestsEnum&gt; interests; } I am using Hibernate JPA implementation, but of course would prefer implem...


c# - garbage collection Operation

Can someone please explain me how garbage collection is working? (I'm using C# and Java).


Java: Trouble with Generics & Collection type detection

I have a class called DataSet with various constructors, each specifying a different type of variable. It might look a bit like this: public class DataSet { private HashSet Data; public DataSet( DataObject obj ) { Data = new &lt;DataObject&gt;HashSet(); Data.add( obj ); } public DataSet( ObjectRelationship rel ) { Data = new &lt;ObjectRelationship&gt;HashS...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top