java Spring 源码套件 spring3 + Hibernate4 + maven 3 + MySQL 5

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10691486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:07:48  来源:igfitidea点击:

Spring source suite spring3 + Hibernate4 + maven 3 + MySQL 5

javahibernatespring-mvc

提问by user1408682

I am getting an error in my application but I'm not sure what it means. I posted some sample code bellow. This is the error I get:

我在我的应用程序中遇到错误,但我不确定这意味着什么。我在下面发布了一些示例代码。这是我得到的错误:

> SEVERE: Exception sending context initialized event to listener
> instance of class
> org.springframework.web.context.ContextLoaderListener
> org.springframework.beans.factory.BeanCreationException: Error
> creating bean with name 'transactionManager' defined in ServletContext
> resource [/WEB-INF/spring/root-context.xml]: Invocation of init method
> failed; nested exception is
> org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to
> requested type [javax.sql.DataSource]     at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
>   at
> org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:294)
>   at
> org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
>   at
> org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
>   at
> org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
>   at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
>   at
> org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
>   at
> org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
>   at
> org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
>   at
> org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
>   at
> org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
>   at
> org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
>   at
> org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
>   at
> org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
>   at
> org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
>   at
> org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
>   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
>   at java.util.concurrent.FutureTask.run(FutureTask.java:166)     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
>   at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
>   at java.lang.Thread.run(Thread.java:722) Caused by:
> org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to
> requested type [javax.sql.DataSource]     at
> org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.unwrap(DriverManagerConnectionProviderImpl.java:91)
>   at
> org.springframework.orm.hibernate4.SessionFactoryUtils.getDataSource(SessionFactoryUtils.java:101)
>   at
> org.springframework.orm.hibernate4.HibernateTransactionManager.afterPropertiesSet(HibernateTransactionManager.java:264)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
>   ... 22 more
> 
> ERROR: org.springframework.web.context.ContextLoader - Context
> initialization failed
> org.springframework.beans.factory.BeanCreationException: Error
> creating bean with name 'transactionManager' defined in ServletContext
> resource [/WEB-INF/spring/root-context.xml]: Invocation of init method
> failed; nested exception is
> org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to
> requested type [javax.sql.DataSource]     at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
>   at
> org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:294)
>   at
> org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
>   at
> org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
>   at
> org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
>   at
> org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
>   at
> org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
>   at
> org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
>   at
> org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
>   at
> org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
>   at
> org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
>   at
> org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)
>   at
> org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)
>   at
> org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
>   at
> org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
>   at
> org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
>   at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
>   at java.util.concurrent.FutureTask.run(FutureTask.java:166)     at
> java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
>   at
> java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
>   at java.lang.Thread.run(Thread.java:722) Caused by:
> org.hibernate.service.UnknownUnwrapTypeException: Cannot unwrap to
> requested type [javax.sql.DataSource]     at
> org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.unwrap(DriverManagerConnectionProviderImpl.java:91)
>   at
> org.springframework.orm.hibernate4.SessionFactoryUtils.getDataSource(SessionFactoryUtils.java:101)
>   at
> org.springframework.orm.hibernate4.HibernateTransactionManager.afterPropertiesSet(HibernateTransactionManager.java:264)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
>   at
> org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
>   ... 22 more

This is my pom file:

这是我的 pom 文件:

<modelVersion>4.0.0</modelVersion>
<groupId>com.reservosity</groupId>
<artifactId>component</artifactId>
<name>Reservosity</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
    <java-version>1.6</java-version>
    <org.springframework-version>3.1.0.RELEASE</org.springframework-version>
    <org.aspectj-version>1.6.9</org.aspectj-version>
    <org.slf4j-version>1.5.10</org.slf4j-version>
</properties>
<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${org.springframework-version}</version>
        <exclusions>
            <!-- Exclude Commons Logging in favor of SLF4j -->
            <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${org.springframework-version}</version>
    </dependency>

    <!-- AspectJ -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${org.aspectj-version}</version>
    </dependency>

    <!-- Logging -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${org.slf4j-version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${org.slf4j-version}</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.15</version>
        <exclusions>
            <exclusion>
                <groupId>javax.mail</groupId>
                <artifactId>mail</artifactId>
            </exclusion>
            <exclusion>
                <groupId>javax.jms</groupId>
                <artifactId>jms</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jdmk</groupId>
                <artifactId>jmxtools</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.jmx</groupId>
                <artifactId>jmxri</artifactId>
            </exclusion>
        </exclusions>
        <scope>runtime</scope>
    </dependency>

    <!-- @Inject -->
    <dependency>
        <groupId>javax.inject</groupId>
        <artifactId>javax.inject</artifactId>
        <version>1</version>
    </dependency>

    <!-- Servlet -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.3.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>4.1.1.Final</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.1.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2.2</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate.common</groupId>
        <artifactId>hibernate-commons-annotations</artifactId>
        <version>4.0.1.Final</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.20</version>
    </dependency>
    <dependency>
        <groupId>org.javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.15.0-GA</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.1.Final</version>
    </dependency>

    <!-- Test -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.7</version>
        <scope>test</scope>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
                <additionalProjectnatures>
                    <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
                </additionalProjectnatures>
                <additionalBuildcommands>
                    <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
                </additionalBuildcommands>
                <downloadSources>true</downloadSources>
                <downloadJavadocs>true</downloadJavadocs>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.2.1</version>
            <configuration>
                <mainClass>org.test.int1.Main</mainClass>
            </configuration>
        </plugin>
    </plugins>
</build>

The servet-context:

服务器上下文:

<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.reservosity.component.controller" />

The root-context.xml:

根上下文.xml:

<!-- Root Context: defines shared resources visible to all other web components -->


<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation">
        <value>classpath:hibernate.cfg.xml</value>
    </property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />

<bean id="transactionManager"    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

The hibernate.cfg.xml:

hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC 
"-//Hibernate/Hibernate Configuration DTD//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 <hibernate-configuration>
<session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/******</property>
    <property name="hibernate.connection.username">***</property>
    <property name="hibernate.connection.password">***</property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.current_session_context_class">thread</property>
    <mapping class="com.company.component.domain.Company" />
</session-factory>

If I remove the bean transactionManager, it works fine, but when I add it in again, I get that dirty looking error. Not sure why.

如果我删除 bean 事务管理器,它工作正常,但是当我再次添加它时,我会得到那个看起来很脏的错误。不知道为什么。

    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

I am new to spring hibernate and could really do with some help!

我是 Spring Hibernate 的新手,真的可以得到一些帮助!

Thanks

谢谢

Andrew

安德鲁

回答by Mateusz Szulc

I've exactly the same problem. KyelJmD suggests herethat there is a missing connection pooling, and it seems he is right, but he didn't post solution.

我有完全相同的问题。KyelJmD在这里建议缺少连接池,看起来他是对的,但他没有发布解决方案。

So I've spent some time and finaly get it working. To solve this problem you should do two things:

所以我花了一些时间并最终让它工作。要解决这个问题,你应该做两件事:

  1. add these lines into hibernate.cfg.xml file (it's possible that you don't need all of it):

    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">20</property>
    <property name="hibernate.c3p0.timeout">300</property>
    <property name="hibernate.c3p0.max_statements">50</property>
    <property name="hibernate.c3p0.idle_test_period">3000</property>
    
  2. Add this dependencies in pom.xml:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>4.1.9.Final</version>
    </dependency>
    
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.1.9.Final</version>
    </dependency>
    
  1. 将这些行添加到 hibernate.cfg.xml 文件中(您可能不需要全部):

    <property name="hibernate.c3p0.min_size">5</property>
    <property name="hibernate.c3p0.max_size">20</property>
    <property name="hibernate.c3p0.timeout">300</property>
    <property name="hibernate.c3p0.max_statements">50</property>
    <property name="hibernate.c3p0.idle_test_period">3000</property>
    
  2. 在 pom.xml 中添加此依赖项:

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-c3p0</artifactId>
        <version>4.1.9.Final</version>
    </dependency>
    
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>4.1.9.Final</version>
    </dependency>
    

Without maven dependency Hibernate just silently ignores C3P0 configuration.

没有 maven 依赖,Hibernate 只是默默地忽略 C3P0 配置。

With above configuration I dont't get anymore UnknownUnwrapTypeException exception, and it seems it works fine now.

有了上面的配置,我不会再遇到 UnknownUnwrapTypeException 异常了,现在看来它可以正常工作了。

My setup: Spring 3.2.1, Hibernate 4.1.9, Tomcat 7.0.35.

我的设置:Spring 3.2.1、Hibernate 4.1.9、Tomcat 7.0.35。

Dislaimer: as stated in thisquestion, you should rather not use hibernate.cfg.xml file. Use dataSourcebean instead, because, for example, you can use it later for JdbcTemplate.

免责声明:如问题所述,您不应该使用 hibernate.cfg.xml 文件。改用dataSourcebean,因为例如,您可以稍后将它用于 JdbcTemplate。

EDIT :

编辑 :

It's been a while, as I answered this question. It seemed correct, but I never like it, because it was kind of guess, which we should really avoid.

已经有一段时间了,因为我回答了这个问题。这似乎是正确的,但我从不喜欢它,因为这是一种猜测,我们真的应该避免。

So, because I found this interresting and I was unable to find anything in Hibernate 4.1 docs, I tried to proof my and other commenters "guess".

因此,因为我发现这很有趣并且我在 Hibernate 4.1 文档中找不到任何内容,所以我试图证明我和其他评论者“猜测”。

Here is a step-by-step procedure, probably also useful for solving other weird issues in other libraries. Turns out this time it was really easy, what is going on.

这是一个循序渐进的过程,可能对解决其他库中的其他奇怪问题也很有用。原来这一次真的很容易,这是怎么回事。

  1. Create a Maven Project (or use existing one), add Hibernate to dependency (hibernate-entitymanager, I used this time version 4.1.7). Import it into IDE which can automatically attach source code (I used Intellij)
  2. From Stack Trace, find the class where exception (UnknownUnwrapTypeException) has been thrown (DriverManagerConnectionProviderImpl) and navigate there (CTRL-N and type class name), click "Download sources".
  3. Find usages of DriverManagerConnectionProviderImpl(ALT+F7)
  4. Voila! Turns out there is only one usage of DriverManagerConnectionProviderImpl- it is a initiateService(...)method in ConnectionProviderInitiator, which - more or less - tries a couple ConnectionProviderimplementations, before it fallbacks to DriverManagerConnectionProviderImpl, which in our case doesn't work and throws UnknownUnwrapTypeException.
  1. 创建一个 Maven 项目(或使用现有的),将 Hibernate 添加到依赖项(hibernate-entitymanager,我这次使用的是 4.1.7 版本)。将其导入IDE,它可以自动附加源代码(我使用的是Intellij)
  2. 从 Stack Trace 中,找到UnknownUnwrapTypeException抛出异常 ( )的类( DriverManagerConnectionProviderImpl) 并导航到那里(CTRL-N 并输入类名),单击“下载源代码”。
  3. 查找DriverManagerConnectionProviderImpl(ALT+F7) 的用法
  4. 瞧!原来只有一种用法DriverManagerConnectionProviderImpl- 它是 中的一种initiateService(...)方法ConnectionProviderInitiator,它或多或少地尝试了几个ConnectionProvider实现,然后回退到DriverManagerConnectionProviderImpl,在我们的情况下不起作用并抛出UnknownUnwrapTypeException

From Hibernate's ConnectionProviderInitiator.java:

来自 Hibernate 的 ConnectionProviderInitiator.java:

        ConnectionProvider connectionProvider = null;
    String providerClassName = getConfiguredConnectionProviderName( configurationValues );
    if ( providerClassName != null ) {
        connectionProvider = instantiateExplicitConnectionProvider( providerClassName, classLoaderService );
    }
    else if ( configurationValues.get( Environment.DATASOURCE ) != null ) {
        connectionProvider = new DatasourceConnectionProviderImpl();
    }

    if ( connectionProvider == null ) {
        if ( c3p0ConfigDefined( configurationValues ) && c3p0ProviderPresent( classLoaderService ) ) {
            connectionProvider = instantiateExplicitConnectionProvider( C3P0_PROVIDER_CLASS_NAME,
                    classLoaderService
            );
        }
    }

    if ( connectionProvider == null ) {
        if ( proxoolConfigDefined( configurationValues ) && proxoolProviderPresent( classLoaderService ) ) {
            connectionProvider = instantiateExplicitConnectionProvider( PROXOOL_PROVIDER_CLASS_NAME,
                    classLoaderService
            );
        }
    }

    if ( connectionProvider == null ) {
        if ( configurationValues.get( Environment.URL ) != null ) {
            connectionProvider = new DriverManagerConnectionProviderImpl();
        }
    }

    if ( connectionProvider == null ) {
        LOG.noAppropriateConnectionProvider();
        connectionProvider = new UserSuppliedConnectionProviderImpl();
    }

The code roughly shows that:

代码大致表明:

  1. If Environment.DATASOURCE(hibernate.connection.datasource) is set, then DatasourceConnectionProviderImplis used;
  2. If there is c3p0 present, then C3P0 Provider is instantiated
  3. Some other provider is checked (PROXOOL_PROVIDER_CLASS_NAME)
  4. Then if Environment.URL(hibernate.connection.url) is present, we use DriverManagerConnectionProviderImpl.
  1. 如果Environment.DATASOURCE(hibernate.connection.datasource) 已设置,则DatasourceConnectionProviderImpl使用;
  2. 如果存在 c3p0,则实例化 C3P0 Provider
  3. 检查了其他一些提供程序 (PROXOOL_PROVIDER_CLASS_NAME)
  4. 然后如果Environment.URL(hibernate.connection.url) 存在,我们使用DriverManagerConnectionProviderImpl.

And that's it. This explains why if we add C3P0 as Maven Dependency or define DataSource (as Michael ako Tecourtsays in comment below) solves the issue.

就是这样。这解释了为什么如果我们将 C3P0 添加为 Maven 依赖项或定义数据源(正如Michael ako Tecourt在下面的评论中所说)可以解决问题。

Another matter is why DriverManagerConnectionProviderImpl throws UnknownUnwrapTypeException - wheather it is a bug or not - anyway, I don't see any changes in code in Hibernate 4.2.0 and even 4.3.0.Beta.

另一个问题是为什么 DriverManagerConnectionProviderImpl 会抛出 UnknownUnwrapTypeException - 不管它是否是一个错误 - 无论如何,我没有看到 Hibernate 4.2.0 甚至 4.3.0.Beta 中的代码有任何变化。

回答by Alex Barnes

Just looking at the issue it's coming from this code:

看看它来自这个代码的问题:

if ( ConnectionProvider.class.equals( unwrapType ) ||
                DriverManagerConnectionProviderImpl.class.isAssignableFrom( unwrapType ) ) {
            return (T) this;
        }
        else {
            throw new UnknownUnwrapTypeException( unwrapType );
        }

where unwrapType is javax.sql.DataSource.

其中 unwrapType 是javax.sql.DataSource.

Whilst I can't explain exactly what it is about your config that causes this I can suggest a fix.

虽然我无法准确解释导致此问题的配置是什么,但我可以建议修复。

Define a DriverManagerDataSourcebean in your spring application context and then provide this as a property to your LocalSessionFactoryBean. Make sure you remove the datasource configuration from your Hibernate configuration file.

DriverManagerDataSource在您的 spring 应用程序上下文中定义一个bean,然后将其作为属性提供给您的LocalSessionFactoryBean. 确保从 Hibernate 配置文件中删除数据源配置。

回答by hekomobile

try include spring and hibernate library to lib folder to your project. I hope these helps.

尝试将 spring 和 hibernate 库包含到您的项目的 lib 文件夹中。我希望这些有帮助。

回答by Dave Richardson

This articlesuggests that you don't have a datasource defined in your hibernate config file.

本文建议您不要在休眠配置文件中定义数据源。

回答by Altair7852

This article has detailed instruction on Spring 3.1 and Hibernate 4.1 integration:

这篇文章有关于 Spring 3.1 和 Hibernate 4.1 集成的详细说明:

http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/

http://blog.springsource.org/2012/04/06/migrating-to-spring-3-1-and-hibernate-4-1/