Saturday, October 26, 2013

Persistence.xml file in JPA

Persistence.xml 
How will JPA API (EntityManager)  come to know which database to connect, connection parameters,transaction types,logging level etc.? Persistence.xml is a standard configuration file which gives complete flexibility to configure EntityManager

Persistence.xml :-
  1. is to be created under META-INF/persistence.xml
  2. A persistence.xml can contain one or more unique persistence unit names
  3. Persistence units are unique values used by EntityManagerFactory/Entitymanager
  4. Entities ,Connection parameters,logging level ,transaction types etc are declared in persistence.xml

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

The following persistence.xml defines one persistence unit with name JPAExample_Toplink

<persistence version="2.0"
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">

<persistence-unit name="JPAExample_Toplink"
transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>model.Company</class>
<class>model.Department</class>
<class>model.DeptEmpl</class>

<properties>
<property name="javax.persistence.jdbc.password" value="admin" />
<property name="javax.persistence.jdbc.user" value="system" />
<property name="javax.persistence.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:oracle:thin:@localhost:1521:XE" />
<property name="eclipselink.logging.level" value="INFO" />
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
</persistence>

Eclipse automatically creates persistence.xml file when we create a JPA project.It also provides an persistence xml file editor which reduces the manual effort of writing the file.
We can edit :-
Connection
Managed classes
mapping files
Query timeouts









                         Happy Learning

Please provide your valuable comments on this article and share it across your network.


Contact me @ sudheer@javarecent.com orjavarecent@gmail.com

No comments:

Post a Comment

Like and Share