Spring实战中的连接数据库代码
@Configuration
public class DataConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript("schema.sql")
.build();
}
@Bean
public JdbcOperations jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
想通过web console访问这个H2数据库
1、
public class SpitterWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer中添加:
public void onStartup(ServletContext servletContext)
throws ServletException {
super.onStartup(servletContext);
ServletRegistration.Dynamic servlet = servletContext
.addServlet("h2-console", new WebServlet());
servlet.setLoadOnStartup(2);
servlet.addMapping("/console/*");
}
2、打开http://localhost:8080/console访问jdbc:h2:mem:testdb
奇怪的是,直接通过idea的数据库工具连接数据库URL无法连上正确的数据库
参考:
https://sanaulla.info/2017/11/19/configure-embedded-h2-console-with-spring-mvc-application/