通过Spring Boot与H2数据库获取连接

时间:2018-07-13 12:36:52

标签: java spring-boot jdbc h2 spring-jdbc

我正在为数据库使用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(); 

application.properties

 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

1 个答案:

答案 0 :(得分:1)

自动连接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