Hibernate version: 1.2.0.GA
I'm getting NonUniqueObjectExceptions when my session flushes, and it seems to be due to cascade updates adding cascaded entities into the session at the last moment. Here's what seems to be going on:
1. I take detached entity a (of type A), which has not been modified while detached, and "attach" it to the current session using Update().
2. I attach detached entity b (of type B), which has also not been modified while detached, and "attach" it to the current session using Update(). Entity b is not initialized, but since it is reattached, I can now touch it, and it initializes and collections also lazy-load when touched.
3. Entity A has a collection of Bs, including an uninitialized proxy of entity b mentioned in #2.
4. When the session flushes, it seems NHibernate is trying to attach and initialize all the items in the a.B collection to do its cascade update of that collection. But I already attached a different instance of b, so it throws NonUniqueObjectException.
If this is the case, that NHibernate doesn't attach cascade-update entities to the session until flush, is there any reason why it can't attach those entities immediately when Update() is called? If it did, then in step #2 when I try to attach a different copy of b, I can catch NonUniqueObjectException and replace my working instance with the one already in the session. I can't do that if the exception is thrown during Flush().
In general, it has been a nightmare trying to work with detached object trees -- selecting them at one point, when most entities are uninitialized, and then attaching them as needed at later times in different sessions so they can lazy-load and for the uncommon cases where they actually get modified and changes need to be flushed. No matter now careful I try to be in reattaching objects as soon as possible to a new session, I keep running into NonUniqueObjectException, because something else somehow already put an instance with that type's identifier in the session.
Has anyone else had to deal with reattaching detached objects? It seems the problem could be solved if a cache provider could be implemented that obtained instances from my "detached store" ... Has anyone attempted such a cache provider for that purpose?
|