gpt4 book ai didi

jdo:以编程方式在 DataNucleus 中创建多个持久性单元

转载 作者:行者123 更新时间:2023-12-05 00:13:27 25 4
gpt4 key购买 nike

我有两个不同的数据源,我需要两个不同的 PersistenceManagerFactory。这一点我总是可以通过编写一个 persistence.xml 文件来实现。但我希望以编程方式表示它。尽管第二个数据源保持相对不变,但第一个数据源可能会通过插件对其进行添加。这些插件可以带有一个或多个 JDO 注释类。 persitance.xml 在这里不是一个好主意,因为我希望它们在运行时加载。

在 Hibernate(和 JPA)中,这可以通过创建配置对象并向其添加所有带注释的类来实现。每当我看到加载新插件时,我总是可以关闭 SessionFactory 并通过查看 @Entity 注释从插件中重新加载额外的类。

在 DataNucleus/JDO 中有类似的方法吗?

我尝试在 Google 上搜索它,但我最终只找到了 DataNucleus site。解释如何编写 persitence.xml 文件。

最佳答案

下面的 Scala 代码演示了如何动态创建 PersistenceManager。您只需填充 map 并将其传递给 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]

下面您可以看到一个示例,说明在 H2MongoDBPostgreSQL 的情况下,您可能愿意如何填充此类映射:

  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))
}

关于jdo:以编程方式在 DataNucleus 中创建多个持久性单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10384900/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com