【问题标题】:Maven, can't see my h2 classMaven,看不到我的 h2 类
【发布时间】:2016-05-12 20:35:43
【问题描述】:

我的大学项目有些问题

我正在尝试连接到我的 h2 数据库,但我失败了。 我将它包含在 Maven 依赖项中,但它仍然无法正常工作。

    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <version>1.4.186</version>
    </dependency>

我只得到 classnotfoundexception

public class main {
public static void main(String[] a)
{
    Class.forName("org.h2.Driver");
    try (Connection conn = DriverManager.getConnection("jdbc:h2:~/test");
         Statement stat = conn.createStatement()) {
        stat.execute("create table test(id int primary key, name varchar(255))");
        stat.execute("insert into test values(1, 'Hello')");
        try (ResultSet rs = stat.executeQuery("select * from test")) {
            while (rs.next()) {
                System.out.println(rs.getString("name"));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

有什么建议吗?

【问题讨论】:

    标签: maven h2


    【解决方案1】:

    这是失败的,因为 h2 db 驱动程序类在运行时不在类路径中。如果它们不是以某种方式成为应用程序类路径的一部分,则应将它们与应用程序的 jar 文件捆绑在一起。

    使用maven-shade-plugin 或maven-jar-plugin 将依赖项捆绑 与您的应用程序的jar(在本例中称为Uber jar),以使其成为一个独立的可运行的 jar。

    【讨论】:

    • 其实它已经在类路径中了。在我添加public static void main(String[] a) throws Exception 之后,这个问题就消失了。我觉得很奇怪。无论如何,谢谢你
    • 已经在类路径中了,怎么办?您是否以java -cp &lt;h2-driver.jar&gt;:your-jar.jar YourMainClass 的身份运行您的应用程序?
    猜你喜欢
    • 1970-01-01
    • 2011-08-27
    • 2021-01-28
    • 2014-08-15
    • 1970-01-01
    • 2019-07-07
    • 2014-07-29
    • 1970-01-01
    • 2021-10-01
    相关资源
    最近更新 更多