H2數(shù)據庫配置為類似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服務器啟動更早,然后導致這個錯誤的,具體原因還有待查證,解決方案是:
- 創(chuàng)建類
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?