【问题标题】:Including an Entity Class programmatically with a persistence unit?以编程方式包含具有持久性单元的实体类?
【发布时间】:2015-12-23 23:54:03
【问题描述】:

我正在查看我不久前创建的一些代码,并发现了一些奇怪的地方。

由于需要用户输入要读取的数据库的位置,我正在以编程方式创建持久性单元。

我的代码如下

 Map properties = new HashMap();



            db = plan.db;


            // Configure the internal EclipseLink connection pool
            properties.put(TRANSACTION_TYPE, PersistenceUnitTransactionType.RESOURCE_LOCAL.name());
            properties.put(JDBC_DRIVER, "net.ucanaccess.jdbc.UcanaccessDriver");
            properties.put(JDBC_URL, "jdbc:ucanaccess://" + db + ";singleconnection=‌​true;memory=true");
            properties.put(JDBC_USER, "");
            properties.put(JDBC_PASSWORD, "");
          //  properties.put( "provider" , "org.eclipse.persistence.jpa.PersistenceProvider");

           EntityManagerFactory emf2;
            EntityManager em2;

            emf2 = Persistence.createEntityManagerFactory("PU", properties);
            em2 = emf2.createEntityManager();    

有了这个,我可以多次创建我的连接。

我注意到的问题是我的“Persistence.xml”中也有代码

 <persistence-unit name="PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>db.Items</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
  <property name="javax.persistence.jdbc.url" value=""/>
  <property name="javax.persistence.jdbc.user" value=""/>
  <property name="javax.persistence.jdbc.driver" value="net.ucanaccess.jdbc.UcanaccessDriver"/>
  <property name="javax.persistence.jdbc.password" value=""/>
</properties>

现在我注意到我找不到任何方法可以将“实体类”添加到这个“持久性单元”,但是我能够正常运行我的代码,就像这样。

我很好奇它是否只是覆盖了同名持久单元中的旧属性等?它仍然使用“db.Items”的持久性类。

我只是想确保这是正确的方法。

我正在更改我的代码,所以我目前无法运行它以查看是否删除我的 PErsistence.xml 中的所有内容会发生什么,但我对此很好奇。

我还注意到“提供者”属性已被注释掉。我需要发布吗? (它包含在 xml 文件中)。

我还看到一个例子,提到“服务器目标”设置为“否”或其他什么?有什么相关的吗?

谢谢大家

【问题讨论】:

    标签: java jpa entity persistence


    【解决方案1】:

    它会覆盖您在persistence.xml 中指定的属性。例如,您只能以这种方式设置用户名和密码,其他属性将按照文件中的定义使用。我不知道这样做是否“正确”,但我也这样做了。

    Persistence.createEntityManager(unit, props) 的调用首先在类路径中找到的任何persistence.xml 中搜索命名的unit。然后来自props 的属性被添加或覆盖到从该单元的文件中读取的属性中。

    我对你的其他问题没有意见。

    【讨论】:

    • 谢谢,除了指定的属性外,其他一切都保持不变吗?只是想确保我没有创建大量的持久性单元,那会很糟糕,哈哈。我可能不会包含任何属性(我应该将标签留在那里,还是您认为无关紧要)?谢谢!
    猜你喜欢
    • 2011-08-09
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2012-05-25
    相关资源
    最近更新 更多