当前位置: 首页 > 知识库问答 >
问题:

Derby嵌入式数据库不持久化

岑叶秋
2023-03-14

我正在尝试将嵌入式数据库derby与spring框架结合使用。我可以插入数据并读取它。除了数据库没有持久化之外,一切都很好。当我关闭应用程序并再次运行时,数据不存在。我猜数据库是再次创建的,但不知道为什么。

我的代码:

@Configuration
@ComponentScan
@EnableAutoConfiguration

public class MainClass 

{
@Bean
public DataSource dataSource() 
{

        // no need shutdown, EmbeddedDatabaseFactoryBean will take care of this
        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        EmbeddedDatabase db = builder
                .setType(EmbeddedDatabaseType.DERBY) //.HSQL, .H2 or .DERBY
                .setName("some-db")
                .addScript("/create-db.sql")
                .build();
        return db;
}

@Bean
public DataSourceTransactionManager transactionManager(DataSource dataSource)
{
    DataSourceTransactionManager d = new DataSourceTransactionManager(dataSource);
    return d;
}

public static void main(String[] args) 
{

    ConfigurableApplicationContext context = new SpringApplicationBuilder(MainClass.class).headless(false).run(args);
    MainFrame.mf = context.getBean(MainFrame.class);
    MainFrame.mf.setVisible(true);
    UserService userService = new UserService();

    if(userService.isSignedIn())
    {
        MainFrame.mf.loggedIn();
    }
    else
    {
        MainFrame.mf.loggedOut();
    }

}
}

和Spring的输出日志

2017-09-17 20:41:53.461  INFO 3516 --- [           main] com.some.MainClass                      : Starting MainClass on maker with PID 3516 (C:\..\NetbeansProjects\..\target\classes started by verma in C:\..\NetbeansProjects\proj)
2017-09-17 20:41:53.469  INFO 3516 --- [           main] com.some.MainClass                      : No active profile set, falling back to default profiles: default
2017-09-17 20:41:53.571  INFO 3516 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:41:56.974  INFO 3516 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2017-09-17 20:41:57.007  INFO 3516 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2017-09-17 20:41:57.010  INFO 3516 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.16
2017-09-17 20:41:57.278  INFO 3516 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2017-09-17 20:41:57.279  INFO 3516 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3714 ms
2017-09-17 20:41:57.606  INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2017-09-17 20:41:57.616  INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2017-09-17 20:41:57.618  INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2017-09-17 20:41:57.618  INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2017-09-17 20:41:57.619  INFO 3516 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2017-09-17 20:41:58.028  INFO 3516 --- [           main] o.s.j.d.e.EmbeddedDatabaseFactory        : Starting embedded database: url='jdbc:derby:memory:some-db;create=true', username='sa'
2017-09-17 20:41:58.883  INFO 3516 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executing SQL script from class path resource [create-db.sql]
2017-09-17 20:41:59.248  INFO 3516 --- [           main] o.s.jdbc.datasource.init.ScriptUtils     : Executed SQL script from class path resource [create-db.sql] in 365 ms.
2017-09-17 20:42:00.907  INFO 3516 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:42:01.052  INFO 3516 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/login],methods=[POST]}" onto java.util.Map com.some.connection.ConnectionController.login(java.lang.String)
2017-09-17 20:42:01.055  INFO 3516 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/logout],methods=[POST]}" onto org.springframework.http.ResponseEntity com.some.connection.ConnectionController.logout(java.lang.String)
2017-09-17 20:42:01.062  INFO 3516 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-09-17 20:42:01.063  INFO 3516 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-09-17 20:42:01.153  INFO 3516 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.155  INFO 3516 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.250  INFO 3516 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-09-17 20:42:01.717  INFO 3516 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2017-09-17 20:42:01.829  INFO 3516 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-09-17 20:42:01.840  INFO 3516 --- [           main] com.some.MainClass                      : Started MainClass in 9.034 seconds (JVM running for 9.794)
2017-09-17 20:42:06.305  INFO 3516 --- [       Thread-6] ationConfigEmbeddedWebApplicationContext : Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@2df32bf7: startup date [Sun Sep 17 20:41:53 IST 2017]; root of context hierarchy
2017-09-17 20:42:06.314  INFO 3516 --- [       Thread-6] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2017-09-17 20:42:06.348  INFO 3516 --- [       Thread-6] o.s.j.d.e.EmbeddedDatabaseFactory        : Shutting down embedded database: url='jdbc:derby:memory:some-db;create=true'

create-db.sql内容是

CREATE TABLE table_connection
(
id BIGINT PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
ip VARCHAR(50) UNIQUE,
sessionId VARCHAR(50) DEFAULT NULL
);

解决方案:接受的答案指向正确的方向,但误差为db;create=true无法启动。然后,我查看了Netbeans IDE是如何创建derby连接的。问题是create=true,我认为它不应该与url一起发送,而是与如下代码所示的属性一起发送:

@Bean
public DataSource dataSource()
{
    DriverManagerDataSource dm = new DriverManagerDataSource("jdbc:derby:some-db", "root", "root");

    Properties properties = new Properties();
    properties.setProperty("create", "true");

    dm.setConnectionProperties(properties);
    dm.setSchema("APP");
    dm.setDriverClassName("org.apache.derby.jdbc.EmbeddedDriver");

    return dm;
}

@Bean(name="Application.dataSourceInitializer")
public DataSourceInitializer dataSourceInitializer(DataSource dataSource) 
{
    final DataSourceInitializer initializer = new DataSourceInitializer();
    initializer.setDataSource(dataSource);
    try
    {
        JdbcTemplate jdbc = new JdbcTemplate(dataSource);
        jdbc.queryForList("SELECT id FROM table_connection");
    }
    catch(Exception e)
    {
        initializer.setDatabasePopulator(databasePopulator());
    }
    return initializer;
}

@Value("classpath:create-db.sql")
private Resource schemaScript;

private DatabasePopulator databasePopulator() 
{
    final ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    populator.addScript(schemaScript);
    return populator;
}

脚本创建数据库。若表在derby中已经存在,sql会给出错误信息,所以将其包装在try-catch中。

Bean datasourceInitializer被显式命名为“Application”。“dataSourceInitializer”作为spring自动配置往往会覆盖它。在这里检查。

共有1个答案

邢英奕
2023-03-14

这就是你问题的核心:jdbc: derby:内存: thom-db; create=true

当您在Derby JDBC连接URL中说“memory”时,您明确告诉Derby创建一个非持久数据库。

如果从JDBC Connectino URL中删除“memory:”,Derby将在硬盘上的“some db”目录中创建一个持久、持久的数据库。

 类似资料:
  • 我在编译使用嵌入式Derby数据库的java程序时遇到了麻烦。我正在使用Netbeans,并使用了“clean and build”选项,该选项创建了一个dist文件夹。我将数据库添加到dist/resources文件夹中,我将derby连接指向的那个文件夹: 麻烦的是,有些人无法运行程序。对于有些人来说,这就像点击dist文件夹中的.jar文件一样简单。对其他人来说,它根本不会运行。另外,我已经

  • 我正在使用网络逻辑10.3。我正在尝试配置一个持久订阅,其中包含由 jdbc 存储(在 Oracle DB 中)支持的持久消息。我有一个主题,MDB 正在作为持久订阅者侦听该主题。在场景-1下:如果我发送消息,它会命中MDB。 在场景2中:我挂起了MDB,希望发送到主题的消息只要不被MDB(它是唯一注册的持久订阅者)使用,就会一直存在。但是当我向主题发送消息时,它短暂地出现在那里,然后就消失了(我

  • 我正在开发一个Rest API,用于从数据库中获取所有主题。我在Derby中使用Spring Boot,并使用JPA与derby进行交互。启动Spring Boot应用程序时,JPA无法在derby上创建表并抛出错误。 第一个类是实体类,第二个是回购类。

  • 我正在构建一个将使用neo4j的web应用程序。我将在Java构建一个REST API,它将使用Neo4j嵌入式版本。这个架构有什么问题吗? 用别的方法好吗?Neo4j服务器? 谢谢!

  • 我知道以前也有人问过类似的问题并回答过。但我试过了前面的答案的解决方案,但它们并不奏效。我已经尽我所能尝试了,希望有人能为我面临的问题提供一些启示。 在Spring Boot应用程序中配置嵌入式Derby 这是我的代码, 应用程序.属性 ApachederByExample.java 我只是试图在应用程序中使用Apache Derby嵌入式数据库,并且使用Maven中定义的依赖项,我不知道为什么仍

  • 你好,我的同事: Windows7(64位)+Java 8+NetBeans 8.0和使用Derby学习嵌入式数据库。 我遵循一个简单的示例“在NetBeans中使用内置的Derby数据库在NetBeans 6.1中启动一个Java DB应用程序” https://www.youtube.com/watch?v=gcy4mcka8-e https://www.youtube.com/watch?v