以编程方式包含实体类与持久性单元?

时间:2015-09-26 06:08:56

标签: java jpa entity persistence

我正在查看我之前创建的一些代码,并注意到一些奇怪的东西。

我正在以编程方式创建一个持久性单元,因为需要用户输入数据库的位置才能读取。

我的代码如下

 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文件中)。

还有一个例子,我看到提到“服务器目标”设置为“否”或什么?对此有何评论?

全部谢谢

1 个答案:

答案 0 :(得分:2)

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

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

我对你的其他问题没有评论。