【问题标题】:maven hibernate SqlServer unable to load Classmaven hibernate SqlServer 无法加载类
【发布时间】:2021-03-21 17:04:51
【问题描述】:

当我尝试使用 Maven 连接到 SQLServer 时,我有:

Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [com.microsoft.sqlserver.jdbc.SQLServerDriver]

在我的 POM.xml 中,提供了 SQL Server 和 Hibernate 的驱动程序:

<dependencies>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <version>9.2.1.jre15</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.30.Final</version>
        </dependency>
    </dependencies>

这是我的 persistence.xml 的内容:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">

    <persistence-unit name="connect" > 
        <properties> 
            <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://localhost:1433;databasename=warehouse"/> 
            <property name="javax.persistence.jdbc.user" value="user" /> 
            <property name="javax.persistence.jdbc.password" value="password" /> 
            <property name="hibernate.dialect" value="org.hibernate.dialect.SQLServerDialect" /> 
            <property name="hibernate.show_sql" value= "true"/> 
            <property name="hibernate.hbm2ddl.auto" value="update"/> 
        </properties> 
    </persistence-unit> 
</persistence>

当我查看“Maven 依赖项”树时,我有 mssql-jdbc-9.2.1.jre15.jar。当我打开它时,我看到 SQLServerDriver.class :它存在...

我不明白为什么,当我运行我的应用程序时,它告诉我无法加载类 SQLServerDriver

public class MainApp {

    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("connect");

    }

}

【问题讨论】:

    标签: hibernate maven sql-server-2012


    【解决方案1】:

    将依赖项添加到您的 pom.xml 只会使 JAR 可用于您的构建过程,但不一定可用于运行时。你如何运行这个主要方法?如果您使用java -jar,那么您必须了解 JDBC 驱动程序不会重新打包到您的 JAR 文件中,因此您必须将其添加到类路径中。如果您想使用 pom.xml 中的依赖项运行 main 方法,您可以使用 exec-maven-plugin。有关示例,请参见此处:https://www.mojohaus.org/exec-maven-plugin/usage.html#Java_goal

    【讨论】:

    • 非常感谢,我很困惑。我认为使用 POM 中的驱动程序,它会起作用:确实,它必须添加到类路径中。
    猜你喜欢
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多