【问题标题】:Obtain Connection from Spring Boot with H2 Database从 Spring Boot 获取与 H2 数据库的连接
【发布时间】:2018-12-21 20:14:55
【问题描述】:

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

【问题讨论】:

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


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 2020-09-03
      • 2019-12-26
      • 2021-01-06
      • 2020-08-12
      • 2020-02-26
      • 2011-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多