H2数据库配置为类似jdbc:h2:tcp://localhost/~/test/database
的形式,就是Server Mode,如果没有单独启动H2服务器,那么会导致如下错误:
org.h2.jdbc.JdbcSQLException: Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-196]
Caused by: java.net.ConnectException: Connection refused: connect
org.springframework.jdbc.support.MetaDataAccessException: Could not get Connection for extracting meta data; nested exception is org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.h2.jdbc.JdbcSQLException: Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-196]
Caused by: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.h2.jdbc.JdbcSQLException: Connection is broken: "java.net.ConnectException: Connection refused: connect: localhost" [90067-196]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
大概就是连接失败一类的问题,网上说是因为springboot比h2服务器启动更早,然后导致这个错误的,具体原因还有待查证,解决方案是:
- 创建类
Starters
(类名无所谓,后面引用就可以)
import org.h2.tools.Server;
public class Starters {
private static final Logger logger = LoggerFactory.getLogger(Starters.class);
public static void startH2Server() {
try {
Server h2Server = Server.createTcpServer().start(); // 关键代码
if (h2Server.isRunning(true)) {
logger.info("H2 server was started and is running.");
} else {
throw new RuntimeException("Could not start H2 server.");
}
} catch (SQLException e) {
throw new RuntimeException("Failed to start H2 server: ", e);
}
}
}
注意:Springboot默认设置h2的依赖范围是runtime
,需要删除那句代码才能编译时调用org.h2.tools.Server
。
- 分别在SpringBoot启动类
ServletInitializer
和Application
中调用H2 server的启动代码
public class ServletInitializer extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
Starters.startH2Server(); // 关键代码
return application.sources(Application.class);
}
}
@SpringBootApplication
public class Application {
public static void main(String[] args) {
Starters.startH2Server(); // 关键代码
SpringApplication.run(Application.class, args);
}
}
这样修改之后,就可以正常启动了!
参考:How to start H2 TCP server on Spring Boot application startup?