草庐IT

java - 如何显示本地 h2 数据库(Web 控制台)的内容?

coder 2023-05-11 原文

最近我加入了一个新团队,这里的人使用 h2 进行 stub 服务。

我想知道是否可以使用 Web 界面显示此数据库的内容。在工作中,可以通过 localhost:5080

获得

我有一个使用 h2 数据库的项目,但是当我点击 localhost:5080

时看不到 h2 Web 控制台

我也试过 localhost:8082 - 它也不起作用。

我的项目配置(成功运行):

     <bean id="wrappedDataSource" class="net.bull.javamelody.SpringDataSourceFactoryBean">
        <property name="targetName" value="dataSource" />
     </bean>

     <bean id="wrappedDataSource" class="net.bull.javamelody.SpringDataSourceFactoryBean">
            <property name="targetName" value="dataSource" />
        </bean>

        <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
            <property name="driverClassName" value="org.h2.Driver" />
            <property name="url" value="jdbc:h2:~/test;MODE=PostgreSQL" />
            <property name="username" value="sa" />
            <property name="password" value="" />
        </bean>

        <bean id="sessionFactory"
              class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource" ref="wrappedDataSource"/>
            <property name="configLocation">
                <value>classpath:hibernate-test.cfg.xml</value>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.show_sql">false</prop>
                    <prop key="hibernate.connection.charSet">UTF-8</prop>
                    <prop key="hibernate.format_sql">true</prop>
                    <prop key="hbm2ddl.auto">create-drop</prop>
                </props>
            </property>
        </bean>

        <context:property-placeholder location="classpath:jdbc.properties"/>

我不知道如何访问 h2 web 控制台。请帮忙。

附言

我只在 .m2 文件夹中看到提及 h2

附言2

我注意到 http://localhost:8082/ 可以使用 Web 控制台,如果将配置中的 url 替换为:

<property name="url" value="jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL" />

但是如果我已经启动 h2(在 .m2 文件夹中找到 h2 jar 文件并双击),它就可以工作

如果我启动应用程序时没有启动 h2 - 我看到以下错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:94)
    ...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbInitializer': Invocation of init method failed; nested exception is org.hibernate.exception.GenericJDBCException: Could not open connection
    at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:136)
    ...
Caused by: org.hibernate.exception.GenericJDBCException: Could not open connection
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:54)
    ...
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Соединение разорвано: "java.net.ConnectException: Connection refused: connect: localhost"
Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-182])
    at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
    ...
Caused by: org.h2.jdbc.JdbcSQLException: Соединение разорвано: "java.net.ConnectException: Connection refused: connect: localhost"
Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-182]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
    ...
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method)
    ...

如果我启动我的应用程序时它没有启动,我想实现它启动。

附言 3

我尝试编写以下代码:

Server server = null;
try {
    server = Server.createTcpServer("-tcpAllowOthers").start();
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL", "sa", "");
 } catch (Exception e) {
    LOG.error("Error while initialize", e);
 }

在我尝试在浏览器中输入 localhost:9092 之后执行它。

此时下载文件。里面的文件内容如下:

Version mismatch, driver version is “0” but server version is “15”

我的 h2 版本 1.4.182

附言 4

此代码有效:

public class H2Starter extends ContextLoaderListener {
    private static final Logger LOG = LoggerFactory.getLogger(H2Starter.class);

    @Override
    public void contextInitialized(ServletContextEvent event) {

        startH2();
        super.contextInitialized(event);
    }

    private static void startH2() {

        try {
            Server.createTcpServer("-tcpAllowOthers").start();
            Class.forName("org.h2.Driver");
            DriverManager.getConnection("jdbc:h2:tcp://localhost/~/test;MODE=PostgreSQL;AUTO_SERVER=TRUE", "sa", "");

            Server.createWebServer().start();
        } catch (Exception e) {
            LOG.error("cannot start H2 [{}]", e);
        }
    }

    public static void main(String[] args) {
        startH2();
    }
}

但我只需要在具体的 Spring 配置文件激活时调用它(现在它总是有效)

最佳答案

让我们把问题分成两部分。

根据您指定与 H2 的连接方式,您将获得不同的操作模式。

模式有:嵌入式、内存中、服务器。

jdbc:h2:~/testembedded mode 中为您提供 H2 实例. 嵌入式模式的限制是只能通过相同的类加载器和相同的 JVM (proof) 访问

jdbc:h2:mem:test 为您提供内存中的 H2 实例。这也是无法从外部世界访问的。

jdbc:h2:tcp://localhost/test 将启动 H2 服务器,并且可以从 JVM 外部 可访问 server mode但有一个限制 - 需要在建立连接之前启动服务器。

最后一个限制是导致您的 Connection denied: connect: localhost" 异常。

总结一下:

  • 在启动应用程序之前启动 H2 服务器
  • 使用 jdbc:h2:tcp://localhost/test 作为连接字符串
  • ....
  • 编码愉快 :)

更新

刚刚注意到您要在启动应用程序的过程中启动服务器。

您可以通过多种方式执行此操作,具体取决于您如何启动应用程序:

  • 如果您使用的是 maven/gradle,您可以更轻松地添加一些配置文件/任务,以便在应用程序实际启动之前执行它。
  • 如果你必须在java中设置所有东西,我建议你看看这个question

更新 2

如果仅出于开发/调试目的需要连接到本地数据库,我将使用 maven 配置文件设置所有内容。来自 this question 的回答会解决的。

如果您需要在生产环境中访问 H2 数据库(我几乎无法想象有任何用例),最好在 Spring 进行。主要是因为应用容器/环境设置在生产中可能会有所不同(与开发环境相比)。

要解决有关是否在 Spring 上下文之外启动服务器的问题 - 这完全取决于要求。 您应该注意的一件事是服务器应该在数据源启动之前启动(否则 spring 上下文将不会加载)

更新 3

很遗憾,我无法为您提供可行的解决方案,但根据 JavaDocs,TCP 服务器和 Web 服务器之间存在差异。 仔细查看JavaDoc of H2 Server class .

我猜你应该使用Server.createWebServer()方法来创建服务器(TCP服务器和Web服务器的区别在于

另一个你可以使用的好类 org.h2.tools.Console (JavaDoc here) 只需运行控制台的主要方法,我想应该可以解决所有问题。

关于java - 如何显示本地 h2 数据库(Web 控制台)的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34238142/

有关java - 如何显示本地 h2 数据库(Web 控制台)的内容?的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  5. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  6. ruby-on-rails - Rails 编辑表单不显示嵌套项 - 2

    我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib

  7. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  8. ruby - 解析 RDFa、微数据等的最佳方式是什么,使用统一的模式/词汇(例如 schema.org)存储和显示信息 - 2

    我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i

  9. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  10. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

随机推荐