01 /**
02 *Copyright (c) @2009 by BEA Systems, Inc. All Rights Reserved.
03 */
04 package examples.webapp.servlets.annotations;
05
06
07 import javax.persistence.EntityManager;
08 import javax.persistence.EntityManagerFactory;
09 import javax.persistence.Persistence;
10 import javax.persistence.PersistenceUnit;
11 import javax.servlet.ServletContextEvent;
12 import javax.servlet.ServletContextListener;
13
14
15 /**
16 * This class is a ServletContextListener which demostrate the usage of
17 * annotation in Listener.
18 */
19 public class ContextInitializer implements ServletContextListener {
20 //@PersistenceUnit expresses a dependency on an EntityManagerFactory.
21 //The name of the persistence unit is defined in the persistence.xml file.
22 @PersistenceUnit(unitName = "annotationServlet")
23 private EntityManagerFactory emf_;
24
25 public void contextInitialized(ServletContextEvent servletContextEvent) {
26 EntityManager em = null;
27 try {
28 em = emf_.createEntityManager();
29 em.getTransaction().begin();
30 em.createQuery("delete from Visitor i").executeUpdate();
31 log("delete all vistors.");
32 em.persist(new Visitor("Sarah Lee", "123"));
33 log("added visitor \"Sarah Lee\"");
34 em.persist(new Visitor("John Doe", "123"));
35 log("added visitor \"John Doe\"");
36 em.persist(new Visitor("Giri Bajaj", "123"));
37 log("added visitor \"Giri Bajaj\"");
38 em.getTransaction().commit();
39 } catch (Throwable t) {
40 if (em.getTransaction(). isActive())
41 em.getTransaction().rollback();
42 throw new RuntimeException(t);
43 }
44 finally {
45 if (em != null || em.isOpen()) {
46 em.close();
47 }
48 if (emf_ != null) {
49 emf_.close();
50 }
51 }
52 }
53
54 public void contextDestroyed(ServletContextEvent servletContextEvent) {
55 }
56
57 public void log(String s) {
58 System.out.println("[LoginFilter]: " + s);
59 }
60
61 }
|