Java Reference
In-Depth Information
"select p from Person p order by p.lastName"
);
List
<
Person
>
list
=
query
.
getResultList
();
System
.
out
.
println
(
"There are "
+
list
.
size
() +
" persons:"
);
list
.
forEach
(
p
->
System
.
out
.
println
(
p
.
getFirstName
() +
' '
+
p
.
getLastName
())
);
}
finally
finally
{
iif
(
entityManager
!=
null
null
)
entityManager
.
close
();
iif
(
entityMgrFactory
!=
null
null
)
entityMgrFactory
.
close
();
}
}
}
Besides the annotations, only a bit of configuration is needed. To tell JPA how to access the
database, a configuration file named
persistence.xml
is loaded. This specifies one or more
persistence units
—think of each of these as one set of classes and a relational database to
keep them in—and some other parameters: the JPA Provider to use, and either a JNDI re-
source or the database driver, URL, and username and password (details of JDBC parameters
are discussed in
Connecting to a JDBC Database
). Here's the code you'll need:
<persistence
<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_1_0.xsd"
version=
"1.0"
>
<persistence-unit
<persistence-unit name=
"jpademo"
>
<provider>
<provider>
org.hibernate.ejb.HibernatePersistence
</provider>
</provider>
<exclude-unlisted-classes>
<exclude-unlisted-classes>
false
</exclude-unlisted-classes>
</exclude-unlisted-classes>
<properties>
<!-- Properties for Hibernate -->
<property
<property name=
"hibernate.hbm2ddl.auto"
value=
"create-drop"
//>
<property
<property name=
"hibernate.show_sql"
value=
"true"
//>
<property
<property name=
"hibernate.format_sql"
value=
"false"
//>
<property
<property name=
"hibernate.archive.autodetection"
value=
"class"
//>
<property
<property name=
"hibernate.connection.driver_class"
value=
"org.hsqldb.jdbcDriver"
//>