gpt4 book ai didi

hibernate - JPA 与 H2 数据库的连接

转载 作者:行者123 更新时间:2023-12-02 23:17:21 48 4
gpt4 key购买 nike

我正在使用 JPA 项目开发一个 hibernate,并尝试使用 H2(嵌入式数据库)获取工作 persistence.xml。

持久性.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
version="1.0">

<persistence-unit name="DefaultPersistenceUnit"
transaction-type="RESOURCE_LOCAL">

<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>entity.user</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:h2:/~test" /> -->
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"></property>
<property name="hibernate.connection.driver_class" value="org.h2.Driver" />
<property name="hibernate.connection.password" value="admin" />
<property name="hibernate.connection.username" value="admin" />
</properties>
</persistence-unit>
</persistence>

但是我的这不起作用,我总是收到错误

"Unable to create EntityManagerFactory"

EntityManagerFactory emf = Persistence.createEntityManagerFactory("DefaultPersistenceUnit");

。任何人都可以为我提供工作的 persistence.xml 吗?

最佳答案

你使用Spring吗?如果是这样,只要容器不提供 EntityManagerFactory,您就可以尝试此操作

<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="database" value="H2" />
</bean>
</property>
<property name="persistenceUnitName" value="DefaultPersistenceUnit" />
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.h2.Driver" />
<property name="url" value="jdbc:h2:database/~test" />
<property name="username" value="sa" />
<property name="password" value="" />
</bean>

关于hibernate - JPA 与 H2 数据库的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6965794/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com