Java Reference
In-Depth Information
The Java Naming and Directory Interface (JNDI) is an API we can use to
obtain resources, such as database connections and JMS queues, from a
directory service.
The value of the unitName attribute of the @PersistenceContext annotation refers
to the name we gave our application's Persistence Unit.
We illustrated how to create a Persistence Unit earlier in the chapter.
NetBeans also creates a new instance variable of type javax.transaction.
UserTransaction . This variable is needed since all JPA code must be executed
in a transaction. UserTransaction is part of the Java Transaction API (JTA).
This API allows us to write code that is transactional in nature. Notice that the
UserTransaction instance variable is decorated with the @Resource annotation.
This annotation is used for dependency injection . in this case an instance of a class
of type javax.transaction.UserTransaction will be instantiated automatically at
run-time, without having to do a JNDI lookup or explicitly instantiating the class.
Dependency injection is a new feature of Java EE 5 not present in
previous versions of J2EE, but that was available and made popular in
the Spring framework. With standard J2EE code, it was necessary to write
boilerplate JNDI lookup code very frequently in order to obtain resources.
To alleviate this situation, Java EE 5 made dependency injection part of
the standard.
The next thing we see is that NetBeans added a persist method that will persist a
JPA entity, automatically inserting a new row containing our entity's fields into the
database. As we can see, this method takes an instance of java.lang.Object as its
single parameter. The reason for this is that the method can be used to persist any
JPA entity (although in our example, we will use it to persist only instances of our
Customer entity).
The first thing the generated method does is obtain an instance of javax.naming.
InitialContext by doing a JNDI lookup on java:comp/env . This JNDI name is the
root context for all Java EE 5 components.
The next thing the method does is initiate a transaction by invoking uxt.begin() .
Notice that since the value of the utx instance variable was injected via dependency
injection (by simply decorating its declaration with the @Resource annotation), there
is no need to initialize this variable.
 
Search WWH ::




Custom Search