2

休止状態をテストするための簡単なアプリケーションを作成しようとしています。データベースとしてms sqlサーバーを使用しています

Microsoft の公式サイトから sqljdbc4 をダウンロードし、sts(eclipse) のビルド パスに追加します。 ここに画像の説明を入力

そして、それは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+マウスの左クリック I saw ![ここに画像の説明を入力][2]

したがって、このクラスが存在するという出力を作成できますが、休止状態には表示されません。

手伝って頂けますか?

アップデート

どのようにアプリケーションを呼び出しますか?

私はとてもクラスを持っています:

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 を右クリック -> 次のように実行 -> 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>

ビナイのアップデート

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

st>

内容 sqljdbc.jar 内容 sqljdbc.jar:

解決策:

間違い:

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

右:

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

3 に答える 3

0

次のスニペットは、Microsoft SQL SERVER でデータベースに接続してクエリを実行するのに適しています。Microsoft は、MavenCentral() などのオンライン リポジトリで使用できる jar ファイル 'sqljdbc42.jar' (jdbc ドライバー) を作成していないことに注意してください。したがって、この jar を Microsoft の Web サイトからダウンロードし、プロジェクト ワークスペース ディレクトリに保存する必要があります。「sqljdbc_4.2.6420.100_enu.exe」をダウンロード

ダウンロードしたファイルを解凍し、Microsoft JDBC Driver 4.2 for SQL Server-->sqljdbc_4.2-->enu に移動します。ここにファイル sqljdbc42.jar が表示されます。ファイルをプロジェクト ワークスペースにコピーします。ディレクトリ名「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()
        }
于 2016-03-31T19:24:43.447 に答える