Java Reference
In-Depth Information
Discussion
As mentioned, JPA and Hibernate provide easy, high-level access to databases, and they are
similar enough that they can be treated together for simple cases. Hibernate is an open source
project, originated by Gavin King and now maintained by JBoss. JPA is an official Java spe-
cification, and a “hollow API”; you need one of the many implementations or “providers”
(just as you need a Driver implementation to use JDBC, see
Connecting to a JDBC Data-
base
). Indeed, one of the more common JPA implementations
is
Hibernate.
Hibernate originally required an XML configuration file specifying the “mappings” between,
for example, Java classes and database tables, between fields or properties on the Java entit-
ies and columns in the database. This XML format is considered obsolete, and I do not cover
it here, although many online examples still use it. After Hibernate had been around for some
years, Sun (before Oracle consumed it) began a committee charged with defining what be-
came JPA, a new high-level API to replace its JDO and EJB specs, taking the best of Hibern-
ate and other persistence APIs. JPA settled both on using good defaults throughout, and on
using Java annotations on the source code to specify these mappings. Although the Hibernate
people had started building their own annotations, they wisely decided to adopt the JPA an-
notations, knowing that they'd have to recognize these in order for Hibernate to be usable as
a JPA provider. So, at present, Hibernate recognizes both its own annotations and the JPA
ones; you should use the JPA ones so you can use a different provider if you need to.
The two bare-minimum annotations you need on every data class to be used with JPA (or
Hibernate in annotations mode) are
@Entity
, which goes on the class itself, and
@Id
, which
goes on the primary key field. A minimally annotated class might look like this:
import
import
javax.persistence.*
javax.persistence.*
;
@Entity
public
public class
class
Address
Address
{
private
private
int
int
id
;
private
private
String streetAddress
;
private
private
String city
;
private
private
String country
;
@Id @GeneratedValue
(
strategy
=
GenerationType
.
AUTO
)
public
public
int
int
getId
() {
return
return
id
;
}
// Other accessors and methods omitted for brevity