我正在尝试利用 hibernate 和 h2 创建一个 spring boot 应用程序。根据我在网上找到的信息,这是可以完成的,但我在启动应用程序时遇到问题。 Hibernate 提示它无法连接到我创建的 h2 数据库。
Caused by: org.hibernate.HibernateException: Unable to make JDBC Connection [jdbc:h2:~/todo]
我的理论是,应用程序需要启动才能使数据库可用,但 hibernate 状态不允许应用程序在没有连接的情况下启动。
我的理论正确吗?是否存在类似问题,有人知道如何解决这个问题?
hibernate 配置
**<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<!--Database connection settings -->
<property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:h2:~/todo</property>
<property name="connection.username">username</property>
<property name="connection.password" />
<!--Set the database dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!--Echo all executed SQL to stdout-->
<property name="show_sql">true</property>
<!--Drop and re-create the database schema on startup-->
<property name="hbm2ddl.auto">create</property>
<!--Name the annotated Entity classes -->
<mapping class="com.todo.beans.User" />
</session-factory>
</hibernate-configuration>**
h2 配置
import org.h2.server.web.WebServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfiguration {
@Bean
ServletRegistrationBean h2servletRegistration(){
ServletRegistrationBean registrationBean = new ServletRegistrationBean( new WebServlet());
registrationBean.addUrlMappings("/console/*");
return registrationBean;
}
}
最佳答案
更改 hibernate 配置中的以下属性
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:mem:todo;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
</property>
Problem is with driver class; you may keep url as it is.
关于java - 在 spring/hibernate 中运行 H2 嵌入式数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44296914/