@PersistenceUnit EntityManagerFactory使用不正确的数据库(sun-appserv-samples)
我使用Java和hibernate 4.3。@PersistenceUnit EntityManagerFactory使用不正确的数据库(sun-appserv-samples)
如果我手动创建一个工厂:
entityManagerFactory = Persistence.createEntityManagerFactory("Chat");
一切正常。 JPA使用persistence.xml中指定的数据库。
但是,如果我通过注射获得的EntityManagerFactory:
@PersistenceUnit(unitName = "Chat")
private EntityManagerFactory factory;
JPA创建和使用太阳的appserv-samples数据库。为什么?
顺便提一句,在EntityManagerFactory.getProperties()中,键javax.persistence.jdbc.url ==我的正确数据库。但这种行为被忽略了。
演示项目:https://dl.dropboxusercontent.com/u/55489242/JPATest.zip
的persistence.xml:
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Chat" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/chat_db"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="60" />
<property name="hibernate.c3p0.min_size" value="1" />
<property name="hibernate.c3p0.max_size" value="2" />
<property name="hibernate.c3p0.max_statements" value="50" />
<property name="hibernate.c3p0.timeout" value="0" />
<property name="hibernate.c3p0.acquireRetryAttempts" value="1" />
<property name="hibernate.c3p0.acquireRetryDelay" value="250" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.use_sql_comments" value="true" />
<property name="hibernate.current_session_context_class" value="thread" />
</properties>
</persistence-unit>
</persistence>
或应用程序代码(作为web应用程序)。我认为在第二种情况下,您的应用程序找不到persistence.xml,因此它使用默认的NetBeans数据库。为了解决这个问题,请确保persistence.xml位于META-INF中,后者位于类路径中。
顺便说一句,我会建议你使用maven来建立项目和它的标准项目文件夹布局(层次结构)。在这种情况下,您可以将persistence.xml放置在src/main/resources/persistence.xml路径中。
我写道: 顺便提一句,在EntityManagerFactory.getProperties()中,键javax.persistence.jdbc.url ==我的正确数据库。 加载persistence.xml。 javax.persistence.jdbc.url是正确的。但JPA使用其他数据库。 – wishmaster35
你是通过Spring或其他东西注入entityManager吗?如果是的话你可以发布代码片段吗? –
我使用JavaEE +休眠。我重写了帖子并添加了演示项目。 – wishmaster35