Java Reference
In-Depth Information
Here is how our code looks like after doing this trivial procedure:
package com.ensode.jpaweb;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@PersistenceContext(name = "persistence/LogicalName",
unitName = "jpawebPU")
public class CustomerDAO {
@Resource
private javax.transaction.UserTransaction utx;
protected void persist(Object object) {
try {
Context ctx =
(Context) new javax.naming.InitialContext().
lookup("java:comp/env");
utx.begin();
EntityManager em = (EntityManager)
ctx.lookup("persistence/LogicalName");
em.persist(object);
utx.commit();
} catch (Exception e) {
java.util.logging.Logger.getLogger(
getClass().getName()).log(
java.util.logging.Level.SEVERE,
"exception caught", e);
throw new RuntimeException(e);
}
}
}
All highlighted code is automatically generated by NetBeans. The main thing
NetBeans does here is add a method that will automatically insert a new row in the
database, effectively persisting our entity's properties.
As we can see, NetBeans automatically generates all necessary import
statements. Additionally, our new class is automatically decorated with the @
PersistenceContext annotation. This annotation allows us to declare that our
class depends on an EntityManager (we'll discuss EntityManager in more detail
shortly). The value of its name attribute is a logical name we can use when doing
a JNDI lookup for our EntityManager . NetBeans by default uses persistence/
LogicalName as the value for this property.
 
Search WWH ::




Custom Search