与H2数据库的JPA连接

时间:2011-08-06 09:01:10

标签: hibernate jpa h2

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

的persistence.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>

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

  

“无法创建EntityManagerFactory”

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

。 anyonw能为我提供工作persistence.xml吗?

1 个答案:

答案 0 :(得分:9)

你在使用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>