Created
July 15, 2009 01:37
-
-
Save ikai/147370 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
JDO Persistence Manager in Scala using blocks | |
Sample below works with Google App Engine | |
Sample usage: | |
Persistence.manage { (pm) => | |
val message = new Message("message body here") | |
pm.makePersistent(message) | |
} | |
If we did this the Java way it would look like this: | |
public final class PMF { | |
private static final PersistenceManagerFactory pmfInstance = | |
JDOHelper.getPersistenceManagerFactory("transactions-optional"); | |
private PMF() {} | |
public static PersistenceManagerFactory get() { | |
return pmfInstance; | |
} | |
} | |
This is how it would be used: | |
Greeting greeting = new Greeting(user, content, date); | |
PersistenceManager pm = PMF.get().getPersistenceManager(); | |
try { | |
pm.makePersistent(greeting); | |
} finally { | |
pm.close(); | |
} | |
The Scala implementation just seems a lot more DRY and a perfect use for blocks - in many | |
cases a user will want to edit values inside the managed Persistent block before close is | |
called. Blocks remove the ceremony that is involved with the try/finally block. | |
*/ | |
import javax.jdo.{PersistenceManager, JDOHelper, PersistenceManagerFactory} | |
object Persistence { | |
private val factory: PersistenceManagerFactory = JDOHelper.getPersistenceManagerFactory("transactions-optional") | |
def manager = factory.getPersistenceManager | |
def manage(persistenceClosure: PersistenceManager => Unit) = { | |
val pm = manager | |
try { | |
persistenceClosure(pm) | |
} finally { | |
pm.close | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment