java 在内存数据库中使用 Hibernate 和 H2 时出错
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16417425/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error using Hibernate with H2 in memory database
提问by andPat
I'm working with Hibernate. How can I configure my persistence.xml to have an H2 in-memory database?
我正在使用 Hibernate。如何配置我的 persistence.xml 以拥有 H2 内存数据库?
My persistence.xmlis:
我的persistence.xml是:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
<class>com.mastertheboss.domain.Employee</class>
<class>com.mastertheboss.domain.Department</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect" />
</properties>
</persistence-unit>
</persistence>
But when I run my app I get the following error:
但是当我运行我的应用程序时,我收到以下错误:
Internal Exception: org.h2.jdbc.JdbcSQLException: Table "EMPLOYEE" not found; SQL statement:
SELECT ID, NAME, DEPARTMENT_ID FROM EMPLOYEE [42102-171]
Error Code: 42102
Call: SELECT ID, NAME, DEPARTMENT_ID FROM EMPLOYEE
Query: ReadAllQuery(referenceClass=Employee sql="SELECT ID, NAME, DEPARTMENT_ID FROM EMPLOYEE")
Internal Exception: org.h2.jdbc.JdbcSQLException: Table "EMPLOYEE" not found; SQL statement:
SELECT ID, NAME, DEPARTMENT_ID FROM EMPLOYEE [42102-171]
Error Code: 42102
Call: SELECT ID, NAME, DEPARTMENT_ID FROM EMPLOYEE
Query: ReadAllQuery(referenceClass=Employee sql="SELECT ID, NAME, DEPARTMENT_ID FROM EMPLOYEE")
回答by Barry NL
You should set hibernate.hbm2ddl.auto property to "create" the first time you run your application, to create the tables
您应该在第一次运行应用程序时将 hibernate.hbm2ddl.auto 属性设置为“create”,以创建表
<property name="hibernate.hbm2ddl.auto" value="create" />
and then (if you don't want the tables to be recreated and emptied every time you start) set it to "validate".
然后(如果您不希望每次启动时都重新创建和清空表)将其设置为“验证”。
<property name="hibernate.hbm2ddl.auto" value="validate" />
To create the schema automatically, add if-not-exists to your connection url like this:
要自动创建架构,请将 if-not-exists 添加到您的连接 url 中,如下所示:
<property name="hibernate.connection.url" value="jdbc:h2:~/<filename>;INIT=CREATE SCHEMA IF NOT EXISTS <schema_name>" />