-->

Exception Error: Unable to create requested servic

2019-07-16 05:12发布

问题:

I have spent days trying to resolve this issue, but to no avail. I have already seen the post Unable to create requested service [org.hibernate.service.jta.platform.spi.JtaPlatform], which has the same title, but has not helped in resolving this issue. In addition, the original poster did not respond to requests for additional information.

I am using Eclipse (Kepler) on Windows 64bit, Java EE Spring application with Tomcat 7.0 and Hibernate. I had previously gotten Hibernate working correctly with the SQLite db (temporary db that I was able to read and write to), but was getting locked database errors when multiple requests came into the website (and multiple close to simultaneous access attempts to the DB). As a result, I have attempted to incorporate JTA into my application to handle this situation, but am not able to get it running. I am using maven, here are the maven dependencies:

  <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>

I am using a hibernate.cfg.xml file, which I have displayed here:

<?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>

I am not using a hibernate.properties file; I just have all the settings in the hibernate.cfg.xml file.

I was previously trying to get my own code to work, but now, I moved just to getting an example directly from the hibernate 5.0 user guide to work, but I get the same error. Here is the example that I have taken directly from the user guide at http://docs.jboss.org/hibernate/orm/5.0/userGuide/en-US/html_single/#d5e997 and modified it slightly to:

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();
    }
}

The block of code that is commented out is part of the configuration that I was using before, but went against that here based on a reference to this link for Hibernate 5 (Hibernate 5 :- org.hibernate.MappingException: Unknown entity).

I get a thrown exception and the error in the Title above when it executes the Session session = sessionFactoryInst.openSession() line. Here is the console output until the thrown exception and the stack trace:

    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... com.mchange.v2.c3p0.PoolBackedDataSource@ff5fe45b [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@d7183b2c [ 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 -> com.mchange.v2.c3p0.DriverManagerDataSource@6a9aeabe [ 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

Any help with this issue would be most appreciated. I know that I must have some of the settings incorrect, but it is not clear to me what is wrong, including how the hibernate.connection.datasource, hibernate.jndi.class, and hibernate.jndi.url settings are supposed to be set. Thank you for your help, and let me know if you need any additional information to diagnose this issue.

回答1:

I resolved this issue and needed to specify a different value for hibernate.transaction.jta.platform in hibernate.cfg.xml. I previously thought that the user guide meant that JtaPlatformResolver would automatically pick a JtaPlatform to use. Instead, I am now using atomikos and am now specifying "com.atomikos.icatch.jta.hibernate4.AtomikosPlatform" for the hibernate.transaction.jta.platform property.



回答2:

It must be a kind of bug (I am at Hibernate 5.2.9), that we cannot trigger the right platform using platform property. But fortunately we have an alternative (see manual 23.12. Transactions properties), which seems to work: hibernate.transaction.jta.platform_resolver.

In persistence.xml:

    <property name="hibernate.transaction.jta.platform_resolver"
             value="server.SpringConfDbGlassfishHibernate" />

In server.SpringConfDbGlassfishHibernate.java:

import org.hibernate.engine.transaction.jta.platform.internal.SunOneJtaPlatform;
@Configuration
public class SpringConfDbGlassfishHibernate implements JtaPlatformResolver
{
  @Override
  public JtaPlatform resolveJtaPlatform(Map arg0, ServiceRegistryImplementor arg1) {
    return new SunOneJtaPlatform();
  }
}

Before that transaction were not active:

J org.hibernate.engine.transaction.jta.platform.internal.StandardJtaPlatformResolver
  DEBUG Could not resolve JtaPlatform, using default 
  [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]

Now they do.