使用persistence.xml和hibernate.cfg.xml

时间:2016-06-24 11:19:13

标签: java hibernate jpa

我使用JPA 2.0 + Hibernate 4.3.4

我的persistence.xml

<persistence-unit name="movie-unit">
    <class>com.epam.rudenkov.controller.BookStore</class>

    <properties>
        <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>
    </properties>
</persistence-unit>

我的hibernate.cfg.xml

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.username">postgres</property>
        <property name="hibernate.connection.password">postgres</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</property>

        <property name="connection_pool_size">1</property>

        <property name="hbm2ddl.auto">create</property>

        <property name="show_sql">true</property>

        <mapping class="com.epam.rudenkov.model.Book"/>

    </session-factory>
</hibernate-configuration>

目前我得到例外:

Caused by: javax.persistence.PersistenceException: [PersistenceUnit: movie-unit] Unable to build EntityManagerFactory
Caused by: org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set"}}

问题:

  1. 我是否需要两个xmls才能建立连接?
  2. 如果我不需要hibernate.cfg.xml,persistence.xml应该怎么样?

1 个答案:

答案 0 :(得分:4)

<persistence-unit name="movie-unit">
<class>com.epam.rudenkov.controller.BookStore</class>

<properties>
    <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>

    <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
    <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
    <property name="hibernate.connection.username">postgres</property>
    <property name="hibernate.connection.password">postgres</property>
    <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/postgres</property>

    <property name="connection_pool_size">1</property>

    <property name="hbm2ddl.auto">create</property>

    <property name="show_sql">true</property>

    <mapping class="com.epam.rudenkov.model.Book"/>
</properties></persistence-unit>
  1. 只能使用persistence.xml文件执行此操作。

  2. persistence.xml应该看起来像上面的代码