Matahari
Matahari

Reputation: 109

Obtain Connection from Spring Boot with H2 Database

I am using Spring Boot, H2, and JPA for my DB I can connect to the DB with putting my connection properties into application.properties. But I do not know how to use the connection Spring Boot established for me.

In the code below, I can use conn to run statement etc.

   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

Upvotes: 3

Views: 7706

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44932

Autowire a DataSource available in the Spring context and obtain the connection from there.

@Autowired
private DataSource dataSource;

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

Alternatively you can create a JdbcTemplate

@Autowired
private DataSource dataSource;

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

Upvotes: 7

Related Questions