persistence.xml
is a configuration file used by JPA, Hibernate is one of many implementations of JPA. The contents of this file have information such as the connection url , user , password . In addition to containing mapping of the classes that have become the tables, and this mapping is done through annotations.
Example of a persistence.xml
file:
<?xml version="1.0" encoding="UTF-8"?>
<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="Hello" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.show_sql" value="true" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/Hello"/>
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="root" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
In <persistence-unit name=”Hello” transaction-type=”RESOURCE_LOCAL”>
two important settings are defined here.
In unit name
sets for the application the configuration that will be used. In the same file we can have several different types, like transaction-type
that defines what our transaction type will be, in our case local
. If it was a web application we would not need to control the transaction, the containner (JBoss, GlassFish,) would do that job.
In <provider>org.hibernate.ejb.HibernatePersistence</provider>
indicates which will be the provider of our application. In our case, Hibernate.
The hibernate.show_sql
option enables the display of generated SQL in the console.
In javax.persistence.jdbc.driver
defines what the database connection agent we will be using, we will use MySQL, javax.persistence.jdbc.url
the URL of our database together with the schema of our database.
In javax.persistence.jdbc.user
and javax.persistence.jdbc.password
user and database password. These attributes were defined in the MySQL installation. I used the root
and root
values.
In% with% of the dialect that Hibernate will use. We'll discuss more about this option in future posts, for example, how to automatically generate database script.
This hibernate.dialect
option set to on, Hibernate will update its tables as needed. For example, if the table does not exist it will create ( hibernate.hbm2ddl.auto
), if you added a new column ( CREATE TABLE
).
References:
link
link