users@glassfish.java.net

Unable to add children to detached parent - OptimisticLock

From: <glassfish_at_javadesktop.org>
Date: Fri, 20 Apr 2007 12:22:39 PDT

How do you add new items to a 1-Many on a detched parent object?

Our use case is as follows.
1. Fetch parent (with empty but non-null collection), parent is now detached
2. parent.add( new Child() )
3. parentDao.update( parent )

We receive an OptimisticLockException on the child class when trying to add it to the 1-Many. The same use case all within the same transaction works fine.

Any ideas?

Test Case:
public void doSetup()
{
parent = new Parent()
beginTransaction();
parentDao.persist( parent );
commitTransaction();
}

// this test fails with OptimisticLockException
@Test
public void testAddChildrenAndUpdate()
{
Child c = new Child();
Parent p = parentDao.find( this.parent.getId() );
parent.addChild( c );

beginTransaction();
parentDao.update( parent ); // fails here!
commitTransaction();
}

@Test
public void testAddChildrenAndUpdate()
{
Child c = new Child();
beginTransaction();

Parent p = parentDao.find( this.parent.getId() );
parent.addChild( c );
parentDao.update( parent ); // this works

commitTransaction();
}

class ParentDao
{
public Parent update( Parent p )
{
entityManager.flush();
return entityManager.merge( p );
}
}

As always, any help is greatly appreciated.
[Message sent by forum member 'chichirico' (chichirico)]

http://forums.java.net/jive/thread.jspa?messageID=213462