users@glassfish.java.net

Re: Cleaning out EclipseLink cache between EJBs

From: Laird Nelson <ljnelson_at_gmail.com>
Date: Thu, 1 Dec 2011 12:52:48 -0500

On Wed, Nov 30, 2011 at 12:12 PM, Laird Nelson <ljnelson_at_gmail.com> wrote:

> The general line of attack I had in mind was to deploy a test EJB
> alongside our other EJBs that--when appropriately called--could somehow
> grab ahold of the proper EntityManagerFactory, invoke its getCache()
> method, and then invoke evictAll(). The test harness would ensure that
> this "cache cleaner" EJB would be called in between individual tests.
>

I couldn't (obviously, in hindsight) get a handle on the appropriate
EntityManagerFactory, because of course the cache cleaner bean would have
no way of getting the appropriate EntityManagerFactory since it doesn't
know (by definition) what persistence unit the bean under test is using.

Then I discovered a convenient MBean that EclipseLink exposes.

The following MBean-oriented code seems to work. For anyone else as nuts
as I am, here's the code I'm using:

    try {
      final Collection<MBeanServer> servers =
MBeanServerFactory.findMBeanServer(null);
      if (servers != null && !servers.isEmpty()) {
        for (final MBeanServer server : servers) {
          if (server != null) {
            final Collection<ObjectName> names = server.queryNames(new
ObjectName("*TopLink:Name=Session*,**"), null);
            if (names != null && !names.isEmpty()) {
              for (final ObjectName name : names) {
                if (name != null) {
                  server.invoke(name, "*invalidateAllIdentityMaps*", null,
null);
                }
              }
            }
          }
        }
      }
    } catch (final InstanceNotFoundException kaboom) {
      throw new EJBException(kaboom);
    } catch (final MalformedObjectNameException kaboom) {
      throw new EJBException(kaboom);
    } catch (final MBeanException kaboom) {
      throw new EJBException(kaboom);
    } catch (final ReflectionException kaboom) {
      throw new EJBException(kaboom);
    }

Hope this helps someone else.

Best,
Laird

-- 
http://about.me/lairdnelson