1 package example; 2 3 import java.io.PrintWriter ; 4 import java.io.IOException ; 5 6 import java.util.List ; 7 8 import javax.servlet.http.HttpServlet ; 9 import javax.servlet.http.HttpServletRequest ; 10 import javax.servlet.http.HttpServletResponse ; 11 12 import javax.servlet.ServletException ; 13 14 import javax.persistence.*; 15 16 19 public class CreateServlet extends HttpServlet { 20 @PersistenceContext(name="example") 21 private EntityManager _entityManager; 22 23 public void init() 24 { 25 Course course = null; 26 27 try { 28 course = _entityManager.find(Course.class, new Integer (1)); 29 } catch (Throwable e) { 30 } 31 32 if (course == null) { 33 _entityManager.getTransaction().begin(); 34 35 try { 36 course = new Course("Potions", "Severus Snape"); 37 _entityManager.persist(course); 38 39 course = new Course("Transfiguration", "Minerva McGonagall"); 40 _entityManager.persist(course); 41 42 course = new Course("Defense Against the Dark Arts", "Remus Lupin"); 43 _entityManager.persist(course); 44 } finally { 45 _entityManager.getTransaction().commit(); 46 } 47 } 48 } 49 50 public void service(HttpServletRequest req, HttpServletResponse res) 51 throws java.io.IOException , ServletException 52 { 53 PrintWriter out = res.getWriter(); 54 55 res.setContentType("text/html"); 56 57 Query courseQuery = _entityManager.createQuery("SELECT o FROM Course o"); 58 59 out.println("<h3>Initial Classes</h3>"); 60 61 displayCourses(out, courseQuery); 62 63 Course divination = null; 64 Course creatures = null; 65 66 _entityManager.getTransaction().begin(); 67 68 try { 69 divination = new Course("Divination", "Sybil Trelawney"); 70 71 _entityManager.persist(divination); 73 74 creatures = new Course("Care of Magical Creatures", "Rubeus Hagrid"); 75 76 _entityManager.persist(creatures); 78 79 out.println("<h3>Adding some classes</h3>"); 80 displayCourses(out, courseQuery); 81 } finally { 82 String sql = "SELECT o FROM Course o WHERE o.course=?1"; 84 85 Query findQuery = _entityManager.createQuery(sql); 86 87 findQuery.setParameter(1, "Divination"); 88 divination = (Course) findQuery.getSingleResult(); 89 90 if (divination != null) 91 _entityManager.remove(divination); 92 93 findQuery.setParameter(1, "Care of Magical Creatures"); 94 creatures = (Course) findQuery.getSingleResult(); 95 96 if (creatures != null) 97 _entityManager.remove(creatures); 98 99 _entityManager.getTransaction().commit(); 100 } 101 102 out.println("<h3>Removing the new classes</h3>"); 103 displayCourses(out, courseQuery); 104 } 105 106 private void displayCourses(PrintWriter out, Query query) 107 throws IOException 108 { 109 List list = query.getResultList(); 110 111 for (int i = 0; i < list.size(); i++) { 112 Course course = (Course) list.get(i); 113 114 out.println(course.getCourse() + " is taught by " + 115 course.getTeacher() + "<br>"); 116 } 117 } 118 } 119 | Popular Tags |