下面的 Scala 代码演示了如何PersistenceManager
动态创建一个。您只需填充地图并将其传递给JDOHelper#getPersistenceManagerFactory
.
private val pu = props(db.driver, db.url, db.username, db.password)
private val pmf = JDOHelper.getPersistenceManagerFactory(pu.asJava)
private val pm = pmf.getPersistenceManager.asInstanceOf[JDOPersistenceManager]
下面您可以看到一个示例,说明在和的情况H2
下您可能愿意如何填充此类地图:MongoDB
PostgreSQL
def props(driver: String, url: String, username: String, password: String): Map[String, Any] =
driver match {
case "org.h2.Driver" =>
Map[String, Any](
"javax.jdo.option.Mapping" -> "h2",
"datanucleus.schema.autoCreateAll" -> "true",
"javax.jdo.PersistenceManagerFactoryClass" -> "org.datanucleus.api.jdo.JDOPersistenceManagerFactory",
"javax.jdo.option.ConnectionDriverName" -> driver,
"javax.jdo.option.ConnectionURL" -> url,
"javax.jdo.option.ConnectionUserName" -> username,
"javax.jdo.option.ConnectionPassword" -> password
)
case "org.postgresql.Driver" =>
Map[String, Any](
"datanucleus.schema.autoCreateAll" -> "true",
"javax.jdo.PersistenceManagerFactoryClass" -> "org.datanucleus.api.jdo.JDOPersistenceManagerFactory",
"javax.jdo.option.ConnectionDriverName" -> driver,
"javax.jdo.option.ConnectionURL" -> url,
"javax.jdo.option.ConnectionUserName" -> username,
"javax.jdo.option.ConnectionPassword" -> password,
"javax.jdo.option.RetainValues" -> "true",
"javax.jdo.option.RestoreValues" -> "true",
"javax.jdo.option.Optimistic" -> "true",
"javax.jdo.option.NontransactionalWrite" -> "false",
"javax.jdo.option.NontransactionalRead" -> "true",
"javax.jdo.option.Multithreaded" -> "true",
"javax.jdo.option.IgnoreCache" -> "false"
)
case "mongodb.jdbc.MongoDriver" =>
Map[String, Any](
"javax.jdo.option.Mapping" -> "mongo",
"datanucleus.schema.autoCreateAll" -> "true",
"javax.jdo.PersistenceManagerFactoryClass" -> "org.datanucleus.api.jdo.JDOPersistenceManagerFactory",
"javax.jdo.option.ConnectionDriverName" -> driver,
"javax.jdo.option.ConnectionURL" -> url,
"javax.jdo.option.ConnectionUserName" -> username,
"javax.jdo.option.ConnectionPassword" -> password
)
case _ => throw new IllegalArgumentException(s"unknown driver %s".format(driver))
}