PersistenceException:无法构建实体管理器工厂由ClassNotFound引起

时间:2017-07-20 09:51:23

标签: java hibernate jpa playframework

我正在使用play jpa并遇到了这个。搜索完整的Stackoverflow无法找到解决方案。

我想要的是当localhost:9000被点击时,HomeController应该添加一个表'产品'在db" crud"已经在mysql中创建了。这样就完成了我的第一个jpa计划

这是我的Persistence.xml     

<persistence 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"
         version="2.1">

<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">


<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <non-jta-data-source>DefaultDS</non-jta-data-source>
    <class>models.Product</class>
    <properties>
        <property name="javax.persistence.jdbc.url" 
value="jdbc:mysql://localhost:3306/crud"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" 
value="toor"/>
        <property name="javax.persistence.jdbc.driver" 
value="com.mysql.jdbc.Driver"/>

    </properties>

</persistence-unit>
</persistence>

这是我的application.conf

play.modules.enabled += "play.filters.csrf.CSRFModule"


play.filters.csrf {

  token {
    name = "csrfToken"
    sign = true
  }

  cookie {
    name = null
    secure = ${play.http.session.secure}
    httpOnly = false
  }

  body.bufferSize = ${play.http.parser.maxMemoryBuffer}
  bypassCorsTrustedOrigins = true

  header {
    name = "Csrf-Token"
    protectHeaders {
      Cookie = "*"
      Authorization = "*"
    }
    bypassHeaders {}
  }

  method {
    whiteList = ["GET", "HEAD", "OPTIONS"]
    blackList = []
  }

  contentType {
    whiteList = []
    blackList = []
  }

  errorHandler = null
}

play.crypto.secret="VRZV/ppo<t?;NKZN?
=PE<N;Yie_G^:sxQrL544YEl[fRsrE<:hMbT;Yj<WhG`bS@"


db.default.driver=com.mysql.jdbc.Driver
db.default.url="jdbc:mysql://localhost:3306/crud"
db.default.user=root
db.default.pass=toor
db.default.jndiName=DefaultDS
jpa.default = test

这是stacktrace

play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[PersistenceException: Unable to build entity manager factory]]
    at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:255)
    at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:182)
    at play.core.server.AkkaHttpServer$$anonfun$$nestedInanonfun$executeHandler$1$1.applyOrElse(AkkaHttpServer.scala:252)
    at play.core.server.AkkaHttpServer$$anonfun$$nestedInanonfun$executeHandler$1$1.applyOrElse(AkkaHttpServer.scala:251)
    at scala.concurrent.Future.$anonfun$recoverWith$1(Future.scala:412)
    at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:37)
    at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
    at play.api.libs.streams.Execution$trampoline$.execute(Execution.scala:70)
    at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)
    at scala.concurrent.impl.Promise$DefaultPromise.dispatchOrAddCallback(Promise.scala:312)
Caused by: javax.persistence.PersistenceException: **Unable to build entity manager factory**
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:83)
    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 controllers.HomeController.index(HomeController.java:29)
    at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$2(Routes.scala:174)
    at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:136)
    at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:135)
    at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$8$$anon$2$$anon$1.invocation(HandlerInvoker.scala:110)
    at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:78)
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [models.Product]
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:245)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildHibernateConfiguration(EntityManagerFactoryBuilderImpl.java:1136)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:849)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
    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)
Caused by: java.lang.ClassNotFoundException: **Could not load requested class : models.Product**
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.findClass(ClassLoaderServiceImpl.java:230)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:242)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildHibernateConfiguration(EntityManagerFactoryBuilderImpl.java:1136)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:853)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:425)

Product.java(模型类)

package models;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.*;

@Entity
public class Product {
    private static List<Product> products;
    @Id
    @GeneratedValue
    private String ean;
    @Column
    private String name;

    @Column
    private String description;

    public Product() {
    }

    public Product(String ean, String name, String description) {
        this.ean = ean;
        this.name = name;
        this.description = description;
    }

    public String toString() {
        return String.format("%s -%s", this.ean, this.name);
    }

    static {
        products = new ArrayList<Product>();
        products.add(new Product("11111111", "Clip 1", "description 1"));
        products.add(new Product("22222222", "Clip 2", "description 2"));
        products.add(new Product("33333333", "Clip 3", "description 3"));
        products.add(new Product("44444444", "Clip 4", "description 4"));
        products.add(new Product("55555555", "Clip 5", "description 5"));
    }

    public static List<Product> findAll() {
        return new ArrayList<Product>(products);
    }

    public static Product findByEan(String ean) {
        for (Product candidate : products) {
            if (candidate.ean.equals(ean)) {
                return candidate;
            }
        }
        return null;
    }

    public static List<Product> findByName(String term) {
        final List<Product> results = new ArrayList<Product>();
        for (Product candidate : products) {
            if (candidate.name.toLowerCase().contains(term.toLowerCase())) {
                results.add(candidate);
            }
        }
        return results;
    }

    public static boolean remove(Product product) {
        return products.remove(product);
    }

    public void save() {
        products.remove(findByEan(this.ean));
        products.add(this);
    }

    public static List<Product> getProducts() {
        return products;
    }

    public String getEan() {
        return ean;
    }

    public void setEan(String ean) {
        this.ean = ean;
    }

    public String   getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

}

和Homecontroller.java

package controllers;

import models.Product;
import org.hibernate.jpa.HibernatePersistenceProvider;
import play.data.FormFactory;
import play.libs.concurrent.HttpExecutionContext;
import play.mvc.*;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class HomeController extends Controller {

    private final FormFactory formFactory;
    private final HttpExecutionContext ec;

    @Inject
    public HomeController(FormFactory formFactory, HttpExecutionContext ec) {
        this.formFactory = formFactory;
        this.ec = ec;
    }

    public Result index() {
        //Create a database and add some entries
        Product newproduct=new Product();

        EntityManagerFactory entityManagerFactory= Persistence.createEntityManagerFactory("test");
//Stuck at the above statment
        EntityManager entityManager=entityManagerFactory.createEntityManager();
        entityManager.getTransaction().begin();


        newproduct.setEan("111");
        newproduct.setName("Lapy");
        newproduct.setDescription("Uska description");

        entityManager.persist(newproduct);
        entityManager.getTransaction().commit();

        entityManager.close();
        entityManagerFactory.close();
        return ok(views.html.index.render("Database created check mysql"));
    }
}

EntitymanagerFactory无法加载模型类Product。我在这个网站上尝试了各种解决方案,否则我不会发布。

3 个答案:

答案 0 :(得分:0)

从persistence.xml中删除以下行

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <non-jta-data-source>DefaultDS</non-jta-data-source>

<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">提供

之后
<class>models.Product</class>

答案 1 :(得分:0)

我最终找到了解决方案,创建实体管理器工厂和实体管理器的代码以及开始事务的代码应该写在控制器的构造函数中(我已经用Homecontroller的索引方法编写) 。数据库是在mysql中创建的。

答案 2 :(得分:0)

在META-INF \ persistence.xml中将字符串:DefaultDS修改为DefaultDS