How do I create a persistence.xml file for JPA and Hibernate?

Valter Silva picture Valter Silva · Aug 31, 2011 · Viewed 75.9k times · Source

I'm trying to use Hibernate JPA but I need to create my persistence.xml (so I can use the entity manager correctly). I am unsure of what to create and where to place it.

This is how my hibernate.cfg.xml in 'Core' mode configured. I'm using Eclipse Java EE IDE Web Developers (Indigo Release):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">XXXXXX</property>
        <property name="hibernate.connection.url">jdbc:mysql://<hostname>/<database></property>
        <property name="hibernate.connection.username">XXXXX</property>
        <property name="hibernate.default_schema">XXXXXX</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>

Answer

nir picture nir · Sep 11, 2013

Create a persistence.xml file that resides in the META-INF folder.

Example:

<persistence xmlns="http://java.sun.com/xml/ns/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">
<persistence-unit name="sample">
  <provider>org.hibernate.ejb.HibernatePersistence</provider>
  <jta-data-source>java:/DefaultDS</jta-data-source>
  <mapping-file>ormap.xml</mapping-file>
  <jar-file>MyApp.jar</jar-file>
  <class>org.acme.Employee</class>
  <class>org.acme.Person</class>
  <class>org.acme.Address</class>
  <properties>
     <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
     <property name="hibernate.connection.password">XXXXXX</property>
     <property name="hibernate.connection.url">jdbc:mysql://<hostname>/<database></property>
     <property name="hibernate.connection.username">XXXXX</property>
     <property name="hibernate.default_schema">XXXXXX</property>
     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
   </properties>
  </persistence-unit>
</persistence>