我有两个不同的数据源,我需要两个不同的PersistenceManagerFactory
。我总是可以写一个persistence.xml
文件。但我希望以编程方式表示它。虽然第二个数据源保持相对不变,但第一个数据源可能通过插件添加了它。这些插件可以带有一个或多个JDO注释类。 persitance.xml
在这里不是一个好主意,因为我希望它们在运行时加载。
在Hibernate(以及JPA)中,可以通过创建配置对象并向其添加所有带注释的类来实现。每当我看到一个新的插件被加载时,我总是可以关闭SessionFactory
并通过查看@Entity
注释从插件中重新加载它。
在DataNucleus / JDO中有类似的方法吗?
我尝试在Google上搜索,但我最终都在DataNucleus site解释如何撰写persitence.xml
文件。
答案 0 :(得分:0)
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))
}