我正在查看我不久前创建的一些代码,并注意到一些奇怪的事情。
由于需要用户输入有关要读取的数据库位置的信息,我正在以编程方式创建持久性单元。
我的代码如下
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 中的所有内容会发生什么,但我对此很好奇。
我还注意到“provider”属性被注释掉了。我需要发布那个吗? (它包含在 xml 文件中)。
我还看到一个例子提到“服务器目标”被设置为“否”或其他什么?对此有何评论?
谢谢大家
最佳答案
它会覆盖您在 persistence.xml
中指定的属性。例如,您只能以这种方式设置用户名和密码,其他属性将按照文件中的定义使用。我不知道这样做是否“正确”,但我也这么做了。
对 Persistence.createEntityManager(unit, props)
的调用首先在以下位置的任何 persistence.xml
中搜索指定的 unit
类路径。然后,将 props
中的属性添加或覆盖到从该单元的文件中读取的属性中。
我对你的其他问题不予置评。
关于java - 以编程方式包含带有持久性单元的实体类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32794203/