CuriousMind CuriousMind - 4 months ago 14
Java Question

property tags in persistence.xml when using JPA

I am new to JPA and use Hibernate as the JPA provider. I came to know that we need

META-INF/persistence.xml
configuration file.

I successfully created a simple Java program to persist data in DB using JPA.

All fine, doubts started when I looked into the
persistence.xml
file to understand it better.

Sample below:



<persistence-unit name="test-jpa" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
<property name="hibernate.connection.url" value="jdbc:h2:tcp://localhost/~/test"/>
<property name="hibernate.connection.username" value="sa" />
<property name="hibernate.connection.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>


The following is the Java code for reading the configuration:

EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test-jpa");


The following are the doubts:


  1. How do we know that Hibernate is the JPA provider? Is it inferred by seeing the property tags in the file?

  2. In config file, there are many
    <property>
    tags, are they pre-defined which can appear in the file (for a given JPA provider) or can we randomly add any property? who reads those
    <property>
    tags?


Answer

A JPA provider would provide documentation that would tell you all of that. Doesn't yours? I'd be surprised.

  1. You should either have a <provider> element in the persistence-unit to define which provider to use, or it would use the default for the environment that you are running in (in JavaSE you would need to have 1 and only one JPA provider in the CLASSPATH, in JavaEE the server would have its own default).

  2. They are provider-specific. Any properties that are prefixed javax.persistence would be JPA STANDARD. The first 4 of those posted have javax.persistence variants that you should have used instead.

Comments