未找到指定的JDBC驱动程序“com.microsoft.sqlserver.jdbc.SQLServerDriver”类

时间:2013-09-11 10:50:36

标签: java hibernate maven

我尝试创建用于测试hibernate的简单应用程序。我使用ms sql server作为数据库

我从microsoft官方网站下载sqljdbc4并添加到我的sts的构建路径(eclipse): enter image description here

它位于maven依赖项

当我调用我的应用程序时,我看到:

SessionFactory creation failed.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver "com.microsoft.sqlserver.jdbc.SQLServerDriver" class not found
Exception in thread "main" java.lang.ExceptionInInitializerError
    at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:22)
    at logic.HibernateUtil.<clinit>(HibernateUtil.java:8)
    at logic.Main.main(Main.java:12)
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver "com.microsoft.sqlserver.jdbc.SQLServerDriver" class not found
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:107)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
    at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
    at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:71)
    at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2277)
    at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2273)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1742)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1782)
    at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
    ... 2 more
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class ["com.microsoft.sqlserver.jdbc.SQLServerDriver"]
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:141)
    at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:104)
    ... 16 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : "com.microsoft.sqlserver.jdbc.SQLServerDriver"
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$1.findClass(ClassLoaderServiceImpl.java:99)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:247)
    at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:138)
    ... 17 more

我不明白这个消息的原因。如果在代码中我写:

com.microsoft.sqlserver.jdbc.SQLServerDriver

然后键入ctrl +鼠标左键我看到了![在此处输入图像描述] [2]

因此我可以输出,这个类存在,但是hibernate没有看到它。

你能帮助我吗?

更新

  

您如何调用您的申请?

我有这样的课程:

import org.hibernate.Session;

public class Main {
    public static void main(String[] args){
        Prepod prepod = new Prepod();
        Student student = new Student();
        prepod.getStudents().add(student);
        student.getPrepods().add(prepod);

        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        session.update(student);
        session.getTransaction().commit();
    }
}

所以:

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            // Configuration configuration = new Configuration().configure(
            // "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
            // return configuration.buildSessionFactory();
            SessionFactory sessionFactory = new Configuration()
                    .configure("/resources/hibernate.cfg.xml").buildSessionFactory();
            return sessionFactory;
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }

}

右键单击Main.java - &gt;运行as-&gt; java应用程序

更新2

项目结构:

![在此输入图片说明] [3]

的pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>hiberTest</groupId>
    <artifactId>hiberTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>myTest</name>
    <description>description</description>
    <properties>
        <hibernate.version>4.2.1.Final</hibernate.version>
        <hibernate-validator.version>4.3.1.Final</hibernate-validator.version>
    </properties>
    <dependencies>

        <!-- <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> 
            <version>${mysql.version}</version> </dependency> -->
        <!-- HIBERNATE -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

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

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey.contribs</groupId>
            <artifactId>jersey-multipart</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.1.4.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
            <version>4.1.4.Final</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>sqljdbc4</artifactId>
            <version>3.0</version>
        </dependency>
    </dependencies>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

为Vinay更新

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

...
C:\Users\Nikolay_Tkachev\.m2> mvn install:install-file -Dfile=sqljdbc4-3.0.jar -DgroupId=com.microsoft.sqlserver -DartifactI
d=sqljdbc4 -Dversion=3.0 -Dpackaging=jar
[INFO] Scanning for projects...
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building Maven Stub Project (No POM) 1
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] --- maven-install-plugin:2.3.1:install-file (default-cli) @ standalone-pom ---
[INFO] Installing C:\Users\Nikolay_Tkachev\.m2\sqljdbc4-3.0.jar to C:\Users\Nikolay_Tkachev\.m2\repository\com\microsoft\sql
server\sqljdbc4\3.0\sqljdbc4-3.0.jar
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.686s
[INFO] Finished at: Wed Sep 11 17:05:35 MSK 2013
[INFO] Final Memory: 3M/90M
[INFO] ------------------------------------------------------------------------
C:\Users\Nikolay_Tkachev\.m2>cd C:\Users\Nikolay_Tkachev\mavenHibernateTest

C:\Users\Nikolay_Tkachev\mavenHibernateTest>mvn eclipse:eclipse
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for hiberTest:hiberTest:jar:0.0.1-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.hibernate:hibernate-core:jar ->
 version 4.0.1.Final vs 4.1.4.Final @ line 45, column 15
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myTest 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> maven-eclipse-plugin:2.9:eclipse (default-cli) @ hiberTest >>>
[INFO]
[INFO] <<< maven-eclipse-plugin:2.9:eclipse (default-cli) @ hiberTest <<<
[INFO]
[INFO] --- maven-eclipse-plugin:2.9:eclipse (default-cli) @ hiberTest ---
[INFO] Using Eclipse Workspace: null
[INFO] Adding default classpath container: org.eclipse.jdt.launching.JRE_CONTAINER
[INFO] File C:\Users\Nikolay_Tkachev\mavenHibernateTest\.project already exists.
       Additional settings will be preserved, run mvn eclipse:clean if you want old settings to be removed.
[INFO] Wrote Eclipse project for "hiberTest" to C:\Users\Nikolay_Tkachev\mavenHibernateTest.
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.061s
[INFO] Finished at: Wed Sep 11 17:07:20 MSK 2013
[INFO] Final Memory: 7M/113M
[INFO] ------------------------------------------------------------------------
C:\Users\Nikolay_Tkachev\mavenHibernateTest>

但我有旧问题((

更新

C:\Users\Nikolay_Tkachev\mavenHibernateTest>
C:\Users\Nikolay_Tkachev\mavenHibernateTest>mvn exec:java -Dexec.mainClass="logic.Main"
[INFO] Scanning for projects...
[WARNING]
[WARNING] Some problems were encountered while building the effective model for hiberTest:hiberTest:jar:0.0.1-SNAPSHOT
[WARNING] 'dependencies.dependency.(groupId:artifactId:type:classifier)' must be unique: org.hibernate:hibernate-core:jar ->
 version 4.0.1.Final vs 4.1.4.Final @ line 45, column 15
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] Building myTest 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO]
[INFO] >>> exec-maven-plugin:1.2.1:java (default-cli) @ hiberTest >>>
[INFO]
[INFO] <<< exec-maven-plugin:1.2.1:java (default-cli) @ hiberTest <<<
[INFO]
[INFO] --- exec-maven-plugin:1.2.1:java (default-cli) @ hiberTest ---
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Initial SessionFactory creation failed.org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver "
com.microsoft.sqlserver.jdbc.SQLServerDriver" class not found
[WARNING]
java.lang.reflect.InvocationTargetException
        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.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:297)
        at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.ExceptionInInitializerError
        at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:18)
        at logic.HibernateUtil.<clinit>(HibernateUtil.java:8)
        at logic.Main.main(Main.java:12)
        ... 6 more
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Specified JDBC Driver "com.microsoft.sqlserver.jdbc
.SQLServerDriver" class not found
        at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnec
tionProviderImpl.java:107)
        at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159
)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:223)
        at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:89)
        at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159
)
        at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
        at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:71)
        at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2277)
        at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2273)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1742)
        at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1782)
        at logic.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
        ... 8 more
Caused by: org.hibernate.service.classloading.spi.ClassLoadingException: Unable to load class ["com.microsoft.sqlserver.jdbc
.SQLServerDriver"]
        at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:141)
        at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnec
tionProviderImpl.java:104)
        ... 22 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : "com.microsoft.sqlserver.jdbc.SQLServerDriver"

        at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl$1.findClass(ClassLoaderServiceImpl.java:99)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
        at java.lang.Class.forName0(Native Method)
        at java.lang.Class.forName(Class.java:247)
        at org.hibernate.service.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:138)
        ... 23 more
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 2.403s
[INFO] Finished at: Wed Sep 11 17:14:07 MSK 2013
[INFO] Final Memory: 6M/115M
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:java (default-cli) on project hiberTest: An excepti
on occured while executing the Java class. null: InvocationTargetException: ExceptionInInitializerError: Specified JDBC Driv
er "com.microsoft.sqlserver.jdbc.SQLServerDriver" class not found: Unable to load class ["com.microsoft.sqlserver.jdbc.SQLSe
rverDriver"]: Could not load requested class : "com.microsoft.sqlserver.jdbc.SQLServerDriver" -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
C:\Users\Nikolay_Tkachev\mavenHibernateTe

映异构体:

内容sqljdbc.jar content sqljdbc.jar:

解决

WRONG

<property name="hibernate.connection.driver_class">"com.microsoft.sqlserver.jdbc.SQLServerD‌​river"</property>

RIGHT:

<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerD‌​river</property>

3 个答案:

答案 0 :(得分:7)

非常简单的错误:

<强>解决方案

WRONG

<property name="hibernate.connection.driver_class">"com.microsoft.sqlserver.jdbc.SQLServerDriver"</property>

RIGHT:

<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>

非常有趣)

答案 1 :(得分:0)

  1. 将sqljdbc驱动程序添加为maven依赖项。请参阅this
  2. 调用mvn eclipse:eclipse
  3. 运行您的应用程序
  4. 我很确定这会解决您的问题。

答案 2 :(得分:0)

以下代码段适用于在Microsoft SQL SERVER中连接和查询数据库。请注意,Microsoft不会在任何在线仓库(如MavenCentral())上提供jar文件'sqljdbc42.jar'(这是jdbc驱动程序)。因此,您需要从Microsoft的网站下载此jar并保存在项目工作区目录中。下载'sqljdbc_4.2.6420.100_enu.exe'

解压缩下载的文件并转到Microsoft JDBC Driver 4.2 for SQL Server - &gt; sqljdbc_4.2 - &gt; enu。在这里,您将看到文件sqljdbc42.jar。将文件复制到项目工作区。我复制到dir名称'lib'。

        repositories {
            flatDir name: 'localRepository', dirs: 'lib'
        }
        configurations {
            driver
        }
        dependencies {
            driver group: 'sql', name: 'sqljdbc42', version:''
        }


        URLClassLoader loader = GroovyObject.class.classLoader
        configurations.driver.each { File file ->
            loader.addURL(file.toURL())
        }

        task connectToCoreDb << {
            def props = [user: 'sa', password: 'shock', allowMultiQueries: 'true'] as Properties
            def connectionUrl = "jdbc:sqlserver://cpt-op-01-db1:1433;databaseName=buds"
            def driver = 'com.microsoft.sqlserver.jdbc.SQLServerDriver'
            def sql = Sql.newInstance(connectionUrl, props, driver)
            sql.eachRow('SELECT name, alias, expiry_date FROM [buds].[dbo].[obj_keystore] ) { row ->
                println "$row.name $row.alias $row.expiry_date"
            }
            logger.info "Closing connection..."
            sql.close()
        }