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 ManyToOneServlet extends HttpServlet { 20 @PersistenceContext(name="example") 21 private EntityManager _entityManager; 22 23 public void init() 24 { 25 House house = null; 26 27 try { 28 house = _entityManager.find(House.class, new Long (1)); 29 } catch (Throwable e) { 30 } 31 32 if (house == null) { 33 _entityManager.getTransaction().begin(); 34 35 try { 36 House gryffindor = new House("Gryffindor"); 37 _entityManager.persist(gryffindor); 38 39 House slytherin = new House("Slytherin"); 40 _entityManager.persist(slytherin); 41 42 House ravenclaw = new House("Ravenclaw"); 43 _entityManager.persist(ravenclaw); 44 45 House hufflepuff = new House("Hufflepuff"); 46 _entityManager.persist(hufflepuff); 47 48 Student student; 49 50 student = new Student("Harry Potter", "M", gryffindor); 51 _entityManager.persist(student); 52 53 student = new Student("Ron Weasley", "M", gryffindor); 54 _entityManager.persist(student); 55 56 student = new Student("Hermione Granger", "F", gryffindor); 57 _entityManager.persist(student); 58 59 student = new Student("Draco Malfoy", "M", slytherin); 60 _entityManager.persist(student); 61 62 student = new Student("Millicent Bulstrode", "F", slytherin); 63 _entityManager.persist(student); 64 65 student = new Student("Penelope Clearwater", "F", ravenclaw); 66 _entityManager.persist(student); 67 } finally { 68 _entityManager.getTransaction().commit(); 69 } 70 } 71 } 72 73 public void service(HttpServletRequest req, HttpServletResponse res) 74 throws java.io.IOException , ServletException 75 { 76 PrintWriter out = res.getWriter(); 77 78 res.setContentType("text/html"); 79 80 Query allStudent = _entityManager.createQuery("SELECT o FROM Student o"); 81 82 List students = allStudent.getResultList(); 83 84 for (int i = 0; i < students.size(); i++) { 85 Student student = (Student) students.get(i); 86 87 out.println(student.getName() + " lives in " + 88 student.getHouse().getName() + "<br>"); 89 } 90 91 String sql = "SELECT s FROM Student s WHERE s.house.name=?1"; 92 93 Query houseStudents = _entityManager.createQuery(sql); 94 houseStudents.setParameter(1, "Gryffindor"); 95 96 students = houseStudents.getResultList(); 97 98 out.println("<h3>Gryffindor Students</h3>"); 99 100 101 for (int i = 0; i < students.size(); i++) { 102 Student student = (Student) students.get(i); 103 104 out.println(student.getName() + "<br>"); 105 } 106 } 107 } 108 | Popular Tags |