Java Reference
In-Depth Information
Java annotations always appear directly before their target. The
@Id
(and many other prop-
erty annotations) can appear either on the field (e.g.,
private int id
) or on the get method
(
getId()
), never on the set method. Within a given project, JPA
requires
you to be consist-
ent: either use field annotations or method annotations, but not both.
There are many annotations, and a full treatment of them is book-length, so consult any good
book on JPA or Hibernate for details.
Once you have annotated your entity classes, and created a bit of XML configuration, you
need to write code using either the JPA or Hibernate APIs to actually load or save data (see
Example 18-1
uses JPA to persist a simple entity object.
Example 18-1. JPASimple
public
public class
class
JPASimple
JPASimple
{
@SuppressWarnings
(
"unchecked"
)
public
public static
static
void
void
main
(
String
[]
args
) {
System
.
out
.
println
(
"JPASimple.main()"
);
EntityManagerFactory entityMgrFactory
=
null
null
;
EntityManager entityManager
=
null
null
;
try
try
{
entityMgrFactory
=
Persistence
.
createEntityManagerFactory
(
"jpademo"
);
entityManager
=
entityMgrFactory
.
createEntityManager
();
EntityTransaction transaction
=
entityManager
.
getTransaction
();
transaction
.
begin
();
// Create an entity in the database.
Person np
=
new
new
Person
(
"Tom"
,
"Boots"
);
System
.
out
.
println
(
np
);
entityManager
.
persist
(
np
);
transaction
.
commit
();
int
int
id
=
np
.
getId
();
System
.
out
.
println
(
"Created Person with Id "
+
id
);
transaction
=
entityManager
.
getTransaction
();
transaction
.
begin
();
Query query
=
entityManager
.
createQuery
(