2012-04-30 63 views
3

我有兩個不同的數據源,我需要兩個不同的數據源PersistenceManagerFactory。我總是可以通過編寫一個persistence.xml文件來獲得。但我希望這是以編程方式表示。儘管第二個數據源保持相對不變,但第一個數據源可能會通過插件增加它。這些插件可以附帶一個或多個JDO註釋類。 A persitance.xml在這裏不是一個好主意,因爲我希望它們在運行時加載。jdo:以編程方式在DataNucleus中創建多個持久性單元

在Hibernate(和JPA)中,通過創建一個配置對象並添加所有帶註釋的類到它是可能的。每當我看到一個新的插件被加載時,我總是可以關閉SessionFactory,並通過查看@Entity註釋來重新加載插件中的額外類。

在DataNucleus/JDO中有類似的方法嗎?

我試着在Google上搜索它,但最終我在DataNucleus site解釋如何編寫persitence.xml文件。

+0

要這麼做?我想創建具有動態數據源的entityManager ... – Alex

回答

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] 

下面你可以看到你如何可能會願意在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)) 
    } 
相關問題