users@glassfish.java.net

Another JPA problem with deleting a _at_ManyToMany relationship

From: <glassfish_at_javadesktop.org>
Date: Tue, 05 Aug 2008 16:56:03 PDT

I have code (probably seen here before) that has a ConfigurationSet and a ConfigurationBundle bidirectional @ManyToMany relationship. I am not using the cascade delete, but rather am removing the relationships manually and then deciding if I can remove an orphaned entity. Basically when I remove a ConfigurationSet, I disconnect the relationship with the ConfigurationBundles and then I check so see if a ConfigurationBundle is no longer associated with a ConfigurationSet and if so, I remove the ConfigurationBundle as well. This all happens in a transaction.

The problem is that periodically, Toplink generates the SQL that will try to remove the ConfigurationBundle before it removes the relationships between the ConfigurationSet and and the ConfigurationBundle. Of course, a referential integrity problem occurs and the transaction is rolled back. The funny thing is that I can retry the same operation (Hit the same button on my web application screen that calls the same SS EJB that performs the action), and sometimes it will then work. Sometimes it will fail for a few tries and then work. No rhyme or reason. It's driving me nuts!

Here is the code that performs the deletion:

        // Iterate through the keys of the bundle map
        Collection<String> bundleNames = new ArrayList<String>(this.configurationBundles.keySet());
        for (String bundleName : bundleNames) {
            // Disconnect the bundle from the configuration set
            ConfigurationBundle bundle = this.configurationBundles.remove(bundleName);
            if (null == bundle) {
                throw new IllegalStateException("failed to remove configuration bundle[" + bundleName + "] from configuration set");
            }
            // Disconnect the configuration set from the bundle
            boolean res = bundle.getConfigurationSets().remove(this);
            if (! res) {
                throw new IllegalStateException("failed to remove configuration set from bundle[" + bundleName + "]");
            }
            // See if there are any more configuration sets referencing this bundle
            if (bundle.getConfigurationSets().isEmpty()) {
                // No more configuration sets so remove the bundle
                em.remove(bundle);
            }
        }

Any help with this will be greatly appreciated!
[Message sent by forum member 'bbergquist' (bbergquist)]

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