javax.persistence.PersistenceException:无法构建实体管理器工厂

Posted

技术标签:

【中文标题】javax.persistence.PersistenceException:无法构建实体管理器工厂【英文标题】:javax.persistence.PersistenceException: Unable to build entity manager factory 【发布时间】:2014-05-20 20:46:11 【问题描述】:

当我尝试创建一个新的 EntityManager 来保存我的数据时,我收到以下错误:

我使用的是 Hibernate 的 JPA-Persistence Provider...

不幸的是,我在 *** / 谷歌搜索中找不到任何有用的帖子...

有人知道错误的原因可能在哪里吗?

感谢您的帮助!

code-sn-ps:

创建实体管理器

EntityManager em;
    EntityManagerFactory fact = Persistence.createEntityManagerFactory("bachelordebug"); // Here it crashes
    em = fact.createEntityManager();

堆栈跟踪

javax.persistence.PersistenceException: Unable to build entity manager factory
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:81)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at com.uzh.platform.api.util.AssignmentUtil.findAll(AssignmentUtil.java:20)
at com.uzh.platform.api.services.GetAssignments.getAssignments(GetAssignments.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:402)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:349)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1010)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:373)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:382)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:345)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:220)
at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:511)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1221)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:156)
at com.thetransactioncompany.cors.CORSFilter.doFilter(CORSFilter.java:233)
at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1212)
at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:399)
at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:766)
at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:450)
at org.mortbay.jetty.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:230)
at org.mortbay.jetty.handler.HandlerCollection.handle(HandlerCollection.java:114)
at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
at org.mortbay.jetty.Server.handle(Server.java:326)
at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:928)
at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:549)
at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:410)
at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
         xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
                    http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="bachelordebug" transaction-type="RESOURCE_LOCAL">
    <!-- <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> -->
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
   <class>com.uzh.platform.data.dao.Assignment</class>
    <properties>
        <property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
        <property name="javax.persistence.jdbc.url" value="jdbc:postgresql://127.0.0.1:5432/bachelor"/>
        <property name="javax.persistence.jdbc.user" value="bachelor"/>
        <property name="javax.persistence.jdbc.password" value="bachelor14"/>
        <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
        <property name="hibernate.hbm2ddl.auto" value="update"/>
        <property name="hibernate.connection.release_mode" value="after_statement"/>
        <property name="connection.pool_size" value="1"/>
        <property name="dialect" value="org.postgresql.Driver"/>
        <property name="current_session_context_class" value="thread"/>
        <property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
        <property name="show_sql" value="true"/>
    </properties>
</persistence-unit>

【问题讨论】:

您的数据库配置可能有问题。尝试使用这些配置使用简单的 java 代码访问数据库。如果您使用的是 maven,请将您的 persistence.xml 放在 \src\main\resources\META-INF\persistence.xml 位置。 感谢杰伊的建议 - 我设法让它在那一秒内工作......:D(见编辑) 如果你拼错了@NamedQuery,它不是显示编译错误吗? 不幸的是没有......另外我应该写“SELECT a FROM Assignment a”而不是“SELECT * FROM Assignment” 【参考方案1】:

(在 cmets 和编辑中回答的问题。见 Question with no answers, but issue solved in the comments (or extended in chat))

OP 写道:

已解决

我终于找到了我的错误!

在我的 JPA-Entity 类中,我拼错了我的 Named-Query 注释(即使我不使用它)

@NamedQuery(name="Assignment.findAll", query ="SELECT * FROM assignment")

当然必须用大写字母来写,即“分配”(即所有术语都像它们出现在服务类中一样!)

这个愚蠢的错误浪费了 3 天 - 但现在我学会了如何去做! :-)

感谢您的帮助!

【讨论】:

【参考方案2】:

我遇到了同样的错误,不幸的是上面的答案对我没有多大帮助。因此,我查看了在我发现此错误的案例中报告的其他错误:

com.mysql.cj.core.exceptions.InvalidConnectionAttributeException: The server time zone value 'EEST' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.

我解决了它指定this 答案,它是 cmets,通过将我的连接 URL 替换为:“jdbc:mysql://localhost:3306/db?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC"

这解决了所有错误,包括这个问题中提到的错误:

javax.persistence.PersistenceException: Unable to build entity manager factory

我希望这可以帮助其他人遇到我遇到的同样问题。

【讨论】:

【参考方案3】:

由于错误可能表明许多不同的原因,因此最好找到原因检查 Hibernate DEBUG 日志语句(我们使用 logback,但它应该在任何其他日志记录框架中类似地工作) :

这样您可以获得大量输出,但可以确定真正有趣的类(很可能您已经在这里发现了原因):

// (logback.groovy)

logger( "org.hibernate", DEBUG )

这对我们来说显示了以下内容(其中 Mapping collection: foo.Bar.field -&gt; some_tab_x 是我们发现错误映射所需的信息):

07:32:43.720 D~ [main ~ main] [     :     ] CollectionSecondPass:SecondPass:  67|  
  Second pass for collection: foo.Bar.field
07:32:43.720 D~ [main ~ main] [     :     ] c.a.CollectionBinder:SecondPass: 823|  
  Binding a OneToMany: foo.Bar.field through a foreign key
07:32:43.720 D~ [main ~ main] [     :     ] c.a.CollectionBinder:SecondPass: 861|  
  Mapping collection: foo.Bar.field -> some_tab_x
07:32:43.727 D~ [main ~ main] [     :     ] ePersistenceProvider:gerFactory:  82|  
  Unable to build entity manager factory
07:32:43.743 E~ [main ~ main] [     :     ] .l.f.m.m.MgFooTstJu:AndRethrow:  74|  
  MyException: unit test error loading Foo with id: 4342153208-2: 
  <java.lang.NullPointerException> => 
  <javax.persistence.PersistenceException: Unable to build entity manager factory>

为了再次限制日志记录(如果有多个地方可以修复您的 JPA 映射),我们随后使用了类似以下内容:

// (logback.groovy)

//logger( "org.hibernate", DEBUG )  // log everything

// infos on annotation mappping, e.g. getting NullPointerExceptions with 
//   javax.persistence.PersistenceException: Unable to build entity manager factory
logger( "org.hibernate.cfg.annotations.CollectionBinder", DEBUG )

(例如在 Eclipse 中只需使用CTRL+SHIFT+T 搜索您要调试的类型,如果日志输出未显示完整的类名)

【讨论】:

【参考方案4】:

在您的实体类中添加 id 注释

@Entity
public class yourClass
  @Id
  private Long id;
  ...
 

【讨论】:

以上是关于javax.persistence.PersistenceException:无法构建实体管理器工厂的主要内容,如果未能解决你的问题,请参考以下文章