Я потратил дни, пытаясь решить эту проблему, но безрезультатно. Я уже видел сообщение Unable to create requested service [org.hibernate.service.jta.platform.spi.JtaPlatform], которое имеет такое же название, но не помогло в решении этой проблемы. Кроме того, первоначальный плакат не ответил на запросы о дополнительной информации.Ошибка исключения: невозможно создать запрошенный сервис [org.hibernate.service.jta.platform.spi.JtaPlatform]
Я использую Eclipse (Kepler) на Windows 64bit, приложение Java EE Spring с Tomcat 7.0 и Hibernate. Я ранее получил Hibernate, работая правильно с SQLite db (временным db, который я смог прочитать и написать), но получал блокированные ошибки базы данных, когда на сайт приходило несколько запросов (и несколько попыток одновременного доступа к БД) , В результате я попытался включить JTA в свое приложение, чтобы справиться с этой ситуацией, но не смог запустить его. Я использую Maven, вот зависимостей Maven:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.1.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.3</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20160212</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.6.2</version>
</dependency>
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.8.11.2</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>5.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss</groupId>
<artifactId>jandex</artifactId>
<version>2.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.20.0-GA</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging</artifactId>
<version>3.3.0.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.logging</groupId>
<artifactId>jboss-logging-annotations</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.jboss.spec.javax.transaction</groupId>
<artifactId>jboss-transaction-api_1.2_spec</artifactId>
<version>1.0.0.Final</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
<version>4.0.4.RELEASE</version>
</dependency>
</dependencies>
Я использую hibernate.cfg.xml файл, который я отображаемую здесь:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">jdbc:sqlite:C:\SB\Desktop\base\rclinicSqlite.db</property>
<property name="hibernate.connection.username"/>
<property name="hibernate.connection.password"/>
<property name="hibernate.connection.datasource">jdbc/rclinicSqlite.db</property>
<property name="hibernate.jndi.class">javax.naming.InitialContext</property>
<property name="hibernate.jndi.url">javax.naming.Context.PROVIDER_URL</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">1</property>
<property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.dataSourceName">jdbc/rclinicSqlite.db</property>
<property name="dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">jta</property>
<property name="hibernate.transaction.jta.platform">org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform</property>
<property name="hibernate.transaction.jta.platform_resolver">org.hibernate.engine.transaction.jta.platform.spi.JtaPlatformResolver</property>
<property name="hibernate.transaction.coordinator_class">jta</property>
</session-factory>
</hibernate-configuration>
Я не используя hibernate.properties файл; У меня есть все настройки в файле hibernate.cfg.xml.
Раньше я пытался заставить свой собственный код работать, но теперь я перешел только для получения примера непосредственно из руководства пользователя hibernate 5.0 для работы, но я получаю ту же ошибку. Вот пример того, что я взял прямо из руководства пользователя на http://docs.jboss.org/hibernate/orm/5.0/userGuide/en-US/html_single/#d5e997 и модифицировал его немного:
public void doSomeWork()
{
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySetting(AvailableSettings.TRANSACTION_COORDINATOR_STRATEGY, "jta");
// Note: depending on the JtaPlatform used and some optional settings,
// the underlying transactions here will be controlled through either
// the JTA TransactionManager or UserTransaction
Connection connection = null;
Session session = null;
try
{
Class.forName("org.sqlite.JDBC");
String sqliteDBPathAndNameStr = "C:\SB\Desktop\base\rclinicSqlite.db";
connection = DriverManager.getConnection("jdbc:sqlite:" + sqliteDBPathAndNameStr);
Statement statement = connection.createStatement();
statement.setQueryTimeout(30); // set timeout to 30 sec.
/*Configuration cf = new Configuration().configure("hibernate.cfg.xml");
cf.addAnnotatedClass(ClientTableObject.class);
cf.addAnnotatedClass(ProfessionalTableObject.class);
ServiceRegistry sr = ssrb.build();
sessionFactoryInst = cf.buildSessionFactory(sr);*/
SessionFactory sessionFactoryInst = new Configuration().configure().buildSessionFactory();
session = sessionFactoryInst.openSession();
//session = sessionFactoryInst.getCurrentSession();
// Since we are in CMT, a JTA transaction would
// already have been started. This call essentially
// no-ops
session.getTransaction().begin();
//doTheWork();
// Since we did not start the transaction (CMT),
// we also will not end it. This call essentially
// no-ops in terms of transaction handling.
session.getTransaction().commit();
}
catch (Exception e) {
// again, the rollback call here would no-op (aside from
// marking the underlying CMT transaction for rollback only).
e.printStackTrace();
// handle the underlying error
}
finally {
session.close();
}
}
Блок кода, который закомментирован является частью конфигурации, которую я использовал раньше, но пошел против что здесь основано на ссылке на эту ссылку для Hibernate 5 (Hibernate 5 :- org.hibernate.MappingException: Unknown entity).
Я получаю исключение и ошибку в названии выше, когда он выполняет сеанс Session session = sessionFactoryInst.openSession(). Вот консольный вывод до тех пор, пока не будет выбрано исключение и трассировка стека:
Mar 30, 2016 1:19:14 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 30, 2016 1:19:15 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator instantiateExplicitConnectionProvider
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.c3p0.internal.C3P0ConnectionProvider
Mar 30, 2016 1:19:15 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: org.sqlite.JDBC at URL: jdbc:sqlite:C:\Users\Sumati Bansal\Desktop\NEEEEW\base\CrunchifySpringMVCTutorial\rclinicSqlite.db
Mar 30, 2016 1:19:15 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001001: Connection properties: {user=, password=****}
Mar 30, 2016 1:19:15 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001003: Autocommit mode: false
Mar 30, 2016 1:19:15 PM com.mchange.v2.log.MLog <clinit>
INFO: MLog clients using java 1.4+ standard logging.
Mar 30, 2016 1:19:17 PM com.mchange.v2.c3p0.C3P0Registry banner
INFO: Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]
Mar 30, 2016 1:19:19 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001007: JDBC isolation level: <unknown>
Mar 30, 2016 1:19:19 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
INFO: Initializing c3p0 pool... [email protected] [ connectionPoolDataSource -> [email protected] [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 1hge17e9f1jtj6b7163wd4v|1c2e958, idleConnectionTestPeriod -> 300, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 3000, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 50, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> [email protected] [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 1hge17e9f1jtj6b7163wd4v|27c6509c, jdbcUrl -> jdbc:sqlite:C:\SB\Desktop\base\rclinicSqlite.db, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> jdbc/rclinicSqlite.db, factoryClassLocation -> null, identityToken -> 1hge17e9f1jtj6b7163wd4v|5e4b6921, numHelperThreads -> 3 ]
Mar 30, 2016 1:19:20 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.SQLiteDialect
Mar 30, 2016 1:19:21 PM org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [2] less than 4
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:244)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:208)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:189)
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.<init>(JtaTransactionCoordinatorImpl.java:84)
at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl.buildTransactionCoordinator(JtaTransactionCoordinatorBuilderImpl.java:28)
at org.hibernate.internal.SessionImpl.<init>(SessionImpl.java:277)
at org.hibernate.internal.SessionFactoryImpl$SessionBuilderImpl.openSession(SessionFactoryImpl.java:1322)
at org.hibernate.internal.SessionFactoryImpl.openSession(SessionFactoryImpl.java:672)
at com.crunchify.controller.RClinicController.doSomeWork(RClinicController.java:741)
at com.crunchify.controller.RClinicController.homeController(RClinicController.java:774)
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.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:781)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:721)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:943)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:877)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:966)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:857)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:842)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [JtaPlatform] as strategy [org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:113)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:162)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDefaultableStrategy(StrategySelectorImpl.java:126)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:120)
at org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator.initiateService(JtaPlatformInitiator.java:40)
at org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator.initiateService(JtaPlatformInitiator.java:26)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:234)
... 46 more
Любая помощь в этом вопросе была бы очень признательна. Я знаю, что некоторые параметры неверны, но мне непонятно, что не так, в том числе, как должны быть установлены настройки hibernate.connection.datasource, hibernate.jndi.class и hibernate.jndi.url , Благодарим вас за помощь и сообщите мне, нужна ли вам дополнительная информация для диагностики этой проблемы.
Я решил эту проблему и мне нужно было указать другое значение для hibernate.transaction.jta.platform в файле hibernate.cfg.xml. Ранее я думал, что руководство пользователя означает, что JtaPlatformResolver автоматически выбирает JtaPlatform для использования. Вместо этого я теперь использую atomikos, и теперь я указываю «com.atomikos.icatch.jta.hibernate4.AtomikosPlatform» для свойства hibernate.transaction.jta.platform. – user2797422