繁体   English   中英

从 Spring Boot 与 H2 数据库获取连接

[英]Obtain Connection from Spring Boot with H2 Database

我正在为我的数据库使用 Spring Boot、H2 和 JPA 我可以通过将我的连接属性放入application.properties来连接到数据库。 但是我不知道如何使用Spring Boot为我建立的连接。

在下面的代码中,我可以使用conn来运行语句等。

   static final String JDBC_DRIVER = "org.h2.Driver";   
   static final String DB_URL = "jdbc:h2:~/test";
   static final String USER = "sa"; 
   static final String PASS = ""; 

Connection conn = null; 
  Statement stmt = null; 
  try { 

     Class.forName(JDBC_DRIVER); 
     conn = DriverManager.getConnection(DB_URL,USER,PASS);  
    //This is what I want to do with spring as I obtain a conn variable and use it.
     stmt = conn.createStatement(); 
     String sql =  "CREATE TABLE   REGISTRATION " + 
        "(id INTEGER not NULL, " + 
        " first VARCHAR(255), " +  
        " last VARCHAR(255), " +  
        " age INTEGER, " +  
        " PRIMARY KEY ( id ))";  
     stmt.executeUpdate(sql);
     stmt.close(); 
     conn.close(); 

应用程序属性

 spring.datasource.url=jdbc:h2:mem:example- 
 app;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
 spring.datasource.platform=h2
 spring.datasource.username = sa
 spring.datasource.password =
 spring.datasource.driverClassName = org.h2.Driver
 spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
 spring.h2.console.enabled=true
 spring.h2.console.path=/console

自动装配 Spring 上下文中可用的DataSource并从那里获取连接。

@Autowired
private DataSource dataSource;

try (Connection conn = dataSource.getConnection()) {
   ...
}

或者,您可以创建一个JdbcTemplate

@Autowired
private DataSource dataSource;

JdbcTemplate template = new JdbcTemplate(dataSource); // should be a separate @Bean

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM