Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从Spring Boot获取与H2数据库的连接_Java_Spring Boot_Jdbc_H2_Spring Jdbc - Fatal编程技术网

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

Java 从Spring Boot获取与H2数据库的连接,java,spring-boot,jdbc,h2,spring-jdbc,Java,Spring Boot,Jdbc,H2,Spring Jdbc,我正在为我的DB使用Spring Boot、H2和JPA,我可以通过将连接属性放入application.properties来连接DB。但我不知道如何使用为我建立的连接弹簧靴 在下面的代码中,我可以使用conn运行语句等 static final String JDBC_DRIVER = "org.h2.Driver"; static final String DB_URL = "jdbc:h2:~/test"; static final String USER = "

我正在为我的DB使用Spring Boot、H2和JPA,我可以通过将连接属性放入
application.properties
来连接DB。但我不知道如何使用为我建立的连接弹簧靴

在下面的代码中,我可以使用
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
Autowire在Spring上下文中可用,并从中获取连接

@Autowired
private DataSource dataSource;

try (Connection conn = dataSource.getConnection()) {
   ...
}
或者,您可以创建一个

@Autowired
private DataSource dataSource;

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