EntityManager не может быть инициализирован в автономном приложении

1

Я получаю исключение, когда пытаюсь проверить свой код. Проблема в том, что EntityManager не может быть инициализирован.

private EntityManager em;

    @BeforeClass
    public void initEntityManager() {
        EntityManagerFactory emf = Persistence
                .createEntityManagerFactory("persistence");
        em = emf.createEntityManager();
    }

Мой persistence.xml выглядит так:

<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
    version="1.0">

    <persistence-unit name="persistence"
        transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" />
            <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://xxx\xxx;" />
            <property name="hibernate.connection.driver_class" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
            <property name="javax.persistence.jdbc.driver"
                value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
            <property name="javax.persistence.jdbc.user" value="user" />
            <property name="javax.persistence.jdbc.password" value="password" />
            <!-- if this is true, hibernate will print (to stdout) the SQL it executes -->
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
        </properties>
    </persistence-unit>
</persistence>

Я получаю это исключение:

java.lang.NoClassDefFoundError: javax/resource/spi/XATerminator
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:247)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:240)
    at org.hibernate.engine.transaction.jta.platform.internal.StandardJtaPlatformResolver.resolveJtaPlatform(StandardJtaPlatformResolver.java:100)
    at org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator.initiateService(JtaPlatformInitiator.java:60)
    at org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator.initiateService(JtaPlatformInitiator.java:43)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:105)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:251)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:225)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:107)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2442)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2438)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1855)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
    at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:397)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
    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)
    at databaseconnectionTest.TestDatabaseConnection.initEntityManager(TestDatabaseConnection.java:17)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassNotFoundException: javax.resource.spi.XATerminator
    at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    ... 46 more

Я не понимаю исключения. Я запутался, потому что тот же код отлично работает, когда я запускаю код на моем Tomcat. Только когда я пытаюсь запустить его как отдельное приложение, я получаю это исключение. В начале он останавливается на

15.07.2014 11:18:51 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
15.07.2014 11:18:52 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLServerDialect

Я пытаюсь найти решение, но не знаю, что делать.

Надеюсь, кто-нибудь может мне помочь.

Johannes

  • 0
    Что ClassNotFound значит для вас? Отсутствует файл JAR в вашем CLASSPATH. java.lang.ClassNotFoundException: javax.resource.spi.XATerminator
  • 0
    Хорошо, но я добавил hibernate-core и hibernate-entitymanager в свой pom. Что мне тоже нужно? И я получаю NoClassDefFoundError и нет ClassNotFoundException.
Показать ещё 1 комментарий
Теги:
hibernate
jpa

1 ответ

0
Лучший ответ

ClassNotFoundException довольно ясен (и должен быть знаком любому, кто использует Java). У вас нет указанного класса в CLASSPATH, поэтому включите банку, которая предоставляет этот класс.

Предложите, чтобы это было вероятно http://central.maven.org/maven2/javax/resource/javax.resource-api/1.7/

  • 0
    Большое спасибо, я добавил это к моей поме, и это работает. Моя проблема заключалась в том, что я был сбит с толку NoClassDefFoundError. <dependency> <groupId> javax.resource </ groupId> <artifactId> connector-api </ artifactId> <версия> 1.5 </ version> <scope> test </ scope> </ dependency>

Ещё вопросы

Сообщество Overcoder
Наверх
Меню