Want Multiple Persistence Contexts in CF9 ORM?

I do.  Because god knows front controllers and persistence layers don't have a one-to-one correspondence.  Turns out that through the magic of application switching you can do it, as long as you're careful with your sessions.  Not going to go into details right now, but this code works (and does what you'd expect):

<cfapplication name="ormtest1" />
<cfset companies = ormExecuteQuery('from Company') />
<cfinclude template="../app1/dsp_home.cfm" />

<cfset ormCloseSession() />

<cfapplication name="ormtest2" />
<cfset people = ormExecuteQuery('from Person') />
<cfinclude template="../app2/dsp_home.cfm" />

Here's the Application.cfc that this snippet runs under:

component {
 this.name = "ormtest3";
}

No ORM awareness at all.

The primary gotcha is that the other applications (ormtest1 and ormtest2) have to have been previously initialized (which you can do with a simple HTTP GET), but this allows you to mix multiple persistence contexts together (much like you can with normal Hibernate), and beat the stupid Application.cfc binding to some degree.  You still can only exist in a single context at any given moment, but you can switch back and forth any place you can close/reopen a session.

And for those of you who are thinking ahead, no, you can't manually manage your session objects instead of letting CF.  You can get a cross-application reference to the SessionFactory without much issue, and you can create a session, and you can even query for entities, but when you get to traversing lazy-loaded relationships it bombs out for some reason.  CF needs to have control over the active session or it doesn't work.  Rather sad, but at least running multi-persistence-context apps is possible, even if not concurrently.

One response to “Want Multiple Persistence Contexts in CF9 ORM?”

  1. Mark Mandel

    That's some very cool stuff!

    You may also want to check my Aussie mate Robin Hilliard Galaxy project for Application context switching in a SOA environment:
    http://trac.rocketboots.com/os/wiki/GalaxySoa

    If you keep experimenting down this road, this could actually be a pretty cool way of managing multiple contexts (if the current thread vs current session issue can be resolved)