Defining a persistence unit

So, JPA is ready in the classpath. What could be the next logical step? It makes sense to define a connection to the database next. The simplest way of doing this is by creating a persistence.xml file. JPA will automatically read this file in the META-INF directory in your classpath. In a Maven project, the location is resources/META-INF/persistence.xml. Inside this file, you can define one or more persistence units (database connections) and its connection properties. The following is an example of a minimal persistence.xml  file you can use to connect to the H2 database:

<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="jpa-example-pu">
<properties>
<property name="javax.persistence.jdbc.url"
value="jdbc:h2:tcp://localhost/~/h2-databases/demo" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>

Since you can define multiple persistence units (when your application needs to connect to multiple databases, for example), each persistence unit must have a name that identifies it. We have used jpa-example-pu for ours. Notice how we used the same connection properties (URL, user, password) we used previously with plain JDBC.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset