2017-09-17 121 views
0

我正嘗試在spring框架中使用嵌入式數據庫derby。我可以插入數據並讀取它。除了數據庫不存在的一件事之外,一切都運行良好。當我關閉應用程序並再次運行時,數據不存在。我猜測數據庫被重新創建,但不知道爲什麼。Derby嵌入式數據庫不會持久

我的代碼:

@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(); 
    } 

} 
} 

和輸出日誌彈簧是

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[email protected]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[email protected]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[email protected]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' 

創建-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 
); 

SOLUTION: 接受的答案中指出正確的方向,但錯誤是一些數據庫;克雷阿te = true未能開始。然後我看了Netbeans IDE如何創建德比連接。問題是創建=真,我認爲這是不應該的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; 
} 

腳本創建-db.sql如果已經存在的表,因爲沒有IF EXISTS可以給錯誤在德比這樣包裹在試試看。

Bean datasourceInitializer被顯式命名爲'Application.dataSourceInitializer',因爲spring自動配置往往會覆蓋它。檢查它here.

+0

因爲它是嵌入式的。嵌入式數據庫與不需要服務器的數據庫一樣,嵌入在應用程序中。這意味着一切都由應用程序管理。如果你關閉你的應用程序,你的數據庫也會關閉。 –

+0

好吧,如果我需要數據來堅持,但不想在客戶端計算機上安裝任何服務器,並且數據對於製作Web服務並不那麼重要,那麼該怎麼辦 – vp131

+0

請嘗試通過以下方式學習Derby的基礎知識: Derby教程:http://db.apache.org/derby/docs/10.13/getstart/ –

回答

0

這是你的問題的核心:jdbc:derby:memory:some-db;create=true

當你說你的德比JDBC連接URL「記憶」,你告訴德比明確地做出非持久數據庫。

如果從JDBC Connectino URL中刪除'memory:',Derby將在硬盤上的'some-db'目錄中創建持久耐用的數據庫。

+0

如何用jdbc:embedded-database創建非內存數據庫?我正在嘗試使用數據源bean的傳統方式,並將它傳遞給jdbc:initialize-database,但它說未能啓動數據庫C:\ some-db?create = true – vp131

+0

也許你可以在你的問題開始一個新的問題「未能啓動數據庫」問題,因爲它與您最初的問題不同。 –

+0

我在編輯中提到過這個。 由於'create = true'屬性而導致無法啓動數據庫'some-db; create = true'。它不應該與數據庫URL一起發送,而是使用Properties對象。我無法在任何地方找到它,而是通過查看Netbeans中的derby數據庫屬性以及它如何創建數據庫來找出它。我應該爲這個問題開始一個新的問題並回答它嗎? – vp131

相關問題