problem with displaying data from hql query

Reply

Join Date: Apr 2007
Posts: 4
Reputation: omesanni is an unknown quantity at this point 
Solved Threads: 0
omesanni omesanni is offline Offline
Newbie Poster

problem with displaying data from hql query

 
0
  #1
Dec 24th, 2008
I am having a with problem displaying the contents of the hql query from the database. Basically I created entity classes for each table in my database.

I have an index.jsp page which has a form in it. When the form is submitted the details are passed to a servlet and the servlet calls a method called findFlights which is in an entity class called FlightItenary. Below is the FlightItenary class:

  1. package flight_search;
  2.  
  3. import java.io.Serializable;
  4. import java.util.Date;
  5. import java.util.List;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8. import javax.persistence.Basic;
  9. import javax.persistence.CascadeType;
  10. import javax.persistence.Column;
  11. import javax.persistence.Entity;
  12. import javax.persistence.EntityManager;
  13. import javax.persistence.EntityManagerFactory;
  14. import javax.persistence.GeneratedValue;
  15. import javax.persistence.GenerationType;
  16. import javax.persistence.Id;
  17. import javax.persistence.NamedQueries;
  18. import javax.persistence.NamedQuery;
  19. import javax.persistence.Query;
  20. import javax.persistence.OneToMany;
  21. import javax.persistence.Persistence;
  22. import javax.persistence.Table;
  23. import javax.persistence.Temporal;
  24. import javax.persistence.TemporalType;
  25.  
  26. /**
  27.  *
  28.  * @author ome
  29.  */
  30. @Entity
  31. @Table(name = "flight_itenary")
  32. @NamedQueries({@NamedQuery(name = "FlightItenary.findAll", query = "SELECT f FROM FlightItenary f"), @NamedQuery(name = "FlightItenary.findById", query = "SELECT f FROM FlightItenary f WHERE f.id = :id"), @NamedQuery(name = "FlightItenary.findByFlightNo", query = "SELECT f FROM FlightItenary f WHERE f.flightNo = :flightNo"), @NamedQuery(name = "FlightItenary.findByDepartureDate", query = "SELECT f FROM FlightItenary f WHERE f.departureDate = :departureDate"), @NamedQuery(name = "FlightItenary.findByArrivalDate", query = "SELECT f FROM FlightItenary f WHERE f.arrivalDate = :arrivalDate"), @NamedQuery(name = "FlightItenary.findByDepartureAirport", query = "SELECT f FROM FlightItenary f WHERE f.departureAirport = :departureAirport"), @NamedQuery(name = "FlightItenary.findByArrivalAirport", query = "SELECT f FROM FlightItenary f WHERE f.arrivalAirport = :arrivalAirport"), @NamedQuery(name = "FlightItenary.findByTotalnum", query = "SELECT f FROM FlightItenary f WHERE f.totalnum = :totalnum")})
  33. public class FlightItenary implements Serializable {
  34. private static final long serialVersionUID = 1L;
  35. @Id
  36. @GeneratedValue(strategy = GenerationType.IDENTITY)
  37. @Basic(optional = false)
  38. @Column(name = "id")
  39. private Integer id;
  40. @Basic(optional = false)
  41. @Column(name = "flight_no")
  42. private String flightNo;
  43. @Basic(optional = false)
  44. @Column(name = "departure_date")
  45. @Temporal(TemporalType.DATE)
  46. private Date departureDate;
  47. @Basic(optional = false)
  48. @Column(name = "arrival_date")
  49. @Temporal(TemporalType.DATE)
  50. private Date arrivalDate;
  51. @Basic(optional = false)
  52. @Column(name = "departure_airport")
  53. private String departureAirport;
  54. @Basic(optional = false)
  55. @Column(name = "arrival_airport")
  56. private String arrivalAirport;
  57. @Column(name = "totalnum")
  58. private Integer totalnum;
  59. @OneToMany(cascade = CascadeType.ALL, mappedBy = "flightId")
  60. private List<FlightClass> flightClassCollection;
  61. @OneToMany(cascade = CascadeType.ALL, mappedBy = "flightId")
  62. private List<FlightPassengers> flightPassengersCollection;
  63. static EntityManagerFactory emf = Persistence.createEntityManagerFactory("AirlinePU");
  64.  
  65.  
  66. public FlightItenary() {
  67. }
  68.  
  69. public FlightItenary(Integer id) {
  70. this.id = id;
  71. }
  72.  
  73. public FlightItenary(Integer id, String flightNo, Date departureDate, Date arrivalDate, String departureAirport, String arrivalAirport) {
  74. this.id = id;
  75. this.flightNo = flightNo;
  76. this.departureDate = departureDate;
  77. this.arrivalDate = arrivalDate;
  78. this.departureAirport = departureAirport;
  79. this.arrivalAirport = arrivalAirport;
  80. }
  81.  
  82. public Integer getId() {
  83. return id;
  84. }
  85.  
  86. public void setId(Integer id) {
  87. this.id = id;
  88. }
  89.  
  90. public String getFlightNo() {
  91. return flightNo;
  92. }
  93.  
  94. public void setFlightNo(String flightNo) {
  95. this.flightNo = flightNo;
  96. }
  97.  
  98. public Date getDepartureDate() {
  99. return departureDate;
  100. }
  101.  
  102. public void setDepartureDate(Date departureDate) {
  103. this.departureDate = departureDate;
  104. }
  105.  
  106. public Date getArrivalDate() {
  107. return arrivalDate;
  108. }
  109.  
  110. public void setArrivalDate(Date arrivalDate) {
  111. this.arrivalDate = arrivalDate;
  112. }
  113.  
  114. public String getDepartureAirport() {
  115. return departureAirport;
  116. }
  117.  
  118. public void setDepartureAirport(String departureAirport) {
  119. this.departureAirport = departureAirport;
  120. }
  121.  
  122. public String getArrivalAirport() {
  123. return arrivalAirport;
  124. }
  125.  
  126. public void setArrivalAirport(String arrivalAirport) {
  127. this.arrivalAirport = arrivalAirport;
  128. }
  129.  
  130. public Integer getTotalnum() {
  131. return totalnum;
  132. }
  133.  
  134. public void setTotalnum(Integer totalnum) {
  135. this.totalnum = totalnum;
  136. }
  137.  
  138. public List<FlightClass> getFlightClassCollection() {
  139. return flightClassCollection;
  140. }
  141.  
  142. public void setFlightClassCollection(List<FlightClass> flightClassCollection) {
  143. this.flightClassCollection = flightClassCollection;
  144. }
  145.  
  146. public List<FlightPassengers> getFlightPassengersCollection() {
  147. return flightPassengersCollection;
  148. }
  149.  
  150. public void setFlightPassengersCollection(List<FlightPassengers> flightPassengersCollection) {
  151. this.flightPassengersCollection = flightPassengersCollection;
  152. }
  153.  
  154. @Override
  155. public int hashCode() {
  156. int hash = 0;
  157. hash += (id != null ? id.hashCode() : 0);
  158. return hash;
  159. }
  160.  
  161. @Override
  162. public boolean equals(Object object) {
  163. // TODO: Warning - this method won't work in the case the id fields are not set
  164. if (!(object instanceof FlightItenary)) {
  165. return false;
  166. }
  167. FlightItenary other = (FlightItenary) object;
  168. if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
  169. return false;
  170. }
  171. return true;
  172. }
  173.  
  174. @Override
  175. public String toString() {
  176. return "flight_search.FlightItenary[id=" + id + "]";
  177. }
  178.  
  179. public void persist(Object object) {
  180. EntityManager em = emf.createEntityManager();
  181. try {
  182. em.getTransaction().begin();
  183. em.persist(object);
  184. em.getTransaction().commit();
  185. } catch (Exception e) {
  186. Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
  187. em.getTransaction().rollback();
  188. } finally {
  189. em.close();
  190. }
  191. }
  192. public static List<FlightItenary> findFlights(String departure, String depart, String arrival, String classType) {
  193. EntityManager em = emf.createEntityManager();
  194. em.getTransaction().begin();
  195. Query q = em.createQuery("select p.departureDate, p.arrivalDate," +
  196. " p.departureAirport, p.arrivalAirport, p.flightNo, p.id from FlightItenary p, FlightClass a where p.id = a.flightId and cast(p.departureDate as string) = :depart" +
  197. " and lower(p.departureAirport)=:departure and lower(p.arrivalAirport)=:arrival and" +
  198. " a.classType=:classType and p.totalnum < 100 ");
  199. q.setParameter("depart", depart);
  200. q.setParameter("arrival", arrival);
  201. q.setParameter("departure", departure);
  202. q.setParameter("classType", classType);
  203. return q.getResultList();
  204. /* Query q = em.createQuery("SELECT f FROM FlightItenary f");
  205.   return q.getResultList();*/
  206. }
  207. }
above you can see the findFlights method which is called from a servlet called Search.java. The findFlights method joins attributes from the FlightItenary class to that of the FlightClass. below is the Search.java servlet where the method is called.


  1. package flight_search;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.text.DateFormat;
  6. import java.text.ParseException;
  7. import java.text.SimpleDateFormat;
  8. import java.util.Date;
  9. import java.util.List;
  10. import java.util.Locale;
  11. import javax.servlet.RequestDispatcher;
  12. import javax.servlet.ServletException;
  13. import javax.servlet.http.HttpServlet;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.servlet.http.HttpServletResponse;
  16.  
  17. /**
  18.  *
  19.  * @author ome
  20.  */
  21. public class Search extends HttpServlet {
  22.  
  23. /**
  24.   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
  25.   * @param request servlet request
  26.   * @param response servlet response
  27.   * @throws ServletException if a servlet-specific error occurs
  28.   * @throws IOException if an I/O error occurs
  29.   */
  30. protected void processRequest(HttpServletRequest request, HttpServletResponse response)
  31. throws ServletException, IOException {
  32. PrintWriter out = response.getWriter();
  33. String departure = request.getParameter("departure").toLowerCase();
  34. String arrival = request.getParameter("arrival").toLowerCase();
  35. String comeback = request.getParameter("comeback");
  36. String depart = request.getParameter("depart");
  37. DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);
  38.  
  39. String d = "";
  40. String ret = "";
  41. try {
  42. Date dep = df.parse(depart);
  43. // out.println(dep);
  44. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  45. d = dateFormat.format(dep);
  46. //out.println(d);
  47. }catch (ParseException e) {
  48. out.println(e);
  49. }
  50.  
  51. String country = request.getParameter("country").toLowerCase();
  52. String classType = request.getParameter("classType").toLowerCase();
  53. String num = request.getParameter("num");
  54.  
  55. if(request.getParameter("oneway")==null) {
  56. List<FlightItenary> flights = FlightItenary.findFlights(departure, d, arrival, classType);
  57.  
  58. try {
  59. Date re = df.parse(comeback);
  60. //out.println(re);
  61. DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  62.  
  63. ret = dateFormat.format(re);
  64. //out.println(ret);
  65. }catch (ParseException e) {
  66. out.println(e);
  67. }
  68. String arr =arrival;
  69. arrival = departure;
  70. departure = arr;
  71. List<FlightItenary> flightRet = FlightItenary.findFlights(departure, ret, arrival, classType);
  72. //out.println(flights.size() + " " + flightRet.size());
  73. if (flights.size() == 0 || flightRet.size()==0) {
  74. request.setAttribute("flights", 0);
  75. // forward request to JSP
  76. String outputPage = "index.jsp";
  77. RequestDispatcher rd = request.getRequestDispatcher(outputPage);
  78. rd.forward(request, response);
  79. }
  80. else {
  81. request.setAttribute("flightsDepart", flights);
  82. request.setAttribute("flightsReturn", flightRet);
  83. String outputPage = "results.jsp";
  84. RequestDispatcher rd = request.getRequestDispatcher(outputPage);
  85. rd.forward(request, response);
  86. }
  87.  
  88. }
  89.  
  90. }
  91.  
  92. // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
  93. /**
  94.   * Handles the HTTP <code>GET</code> method.
  95.   * @param request servlet request
  96.   * @param response servlet response
  97.   * @throws ServletException if a servlet-specific error occurs
  98.   * @throws IOException if an I/O error occurs
  99.   */
  100. @Override
  101. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  102. throws ServletException, IOException {
  103. processRequest(request, response);
  104. }
  105.  
  106. /**
  107.   * Handles the HTTP <code>POST</code> method.
  108.   * @param request servlet request
  109.   * @param response servlet response
  110.   * @throws ServletException if a servlet-specific error occurs
  111.   * @throws IOException if an I/O error occurs
  112.   */
  113.  
  114.  
  115.  
  116. @Override
  117. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  118. throws ServletException, IOException {
  119. processRequest(request, response);
  120. }
  121.  
  122. /**
  123.   * Returns a short description of the servlet.
  124.   * @return a String containing servlet description
  125.   */
  126. @Override
  127. public String getServletInfo() {
  128. return "Short description";
  129. }// </editor-fold>
  130.  
  131. }
In the processrequest method of the servlet, the findFlights method is called and it is passed to a list which of type FlightItenary. After that the result of the list is set to an attribute. The main part of the servlet is in the else statement where the attributes are forwarded to the results.jsp page.Below is results.jsp

  1. <body>
  2. <div class="main">
  3.  
  4. <div id="banner" style=" height: 100px; width: 600px; background: url(images/port.png) no-repeat;">
  5. </div>
  6. <div id="display">
  7. <h1> TO </h1>
  8. <table width="732" height="99" border="0" cellpadding="3" cellspacing="1">
  9. <tr>
  10. <td width="84" class="stylish">Depart</td>
  11. <td width="102" class="stylish">Arrive</td>
  12. <td width="127" class="stylish">From </td>
  13. <td width="108" class="stylish">To</td>
  14. <td width="102" class="stylish">Flight Number </td>
  15. <td width="85" class="stylish">Class of Travel </td>
  16. <td width="74" class="stylish">Select</td>
  17. </tr>
  18. <form name="list" id="list" action="" >
  19. <% int num = 1; %>
  20. <% List fl = (List) request.getAttribute("flightsDepart");
  21. //Iterator it = fl.iterator();
  22. for (Iterator it = fl.iterator(); it.hasNext();) {
  23. FlightItenary fli = (FlightItenary) it.next();
  24. %>
  25. <% String no = Integer.toString(num); %>
  26. <tr>
  27. <td class="text"><%out.print(fli.getDepartureDate());%></td>
  28. <td class="text"><%out.print(fli.getArrivalDate());%></td>
  29. <td class="text"><%out.print(fli.getDepartureAirport());%></td>
  30. <td class="text"><%out.print(fli.getArrivalAirport());%></td>
  31. <td class="text"><%out.print(fli.getFlightNo());%></td>
  32. <td class="text"><%out.print(fli.getClassType());%></td>
  33. <td class="text">
  34. <input name="<% out.print("rad"+no);%>" type="radio" value="<%out.print(fli.getId());%>">
  35. </td>
  36. </tr>
  37. <% } %>
  38. </form>
  39. </table>
  40. </div>
  41.  
  42. </div>
  43. </body>

My problem now is displaying the contents of the query which was carried out in search.java servlet. One of my problem is that I joined entities from the FlightItenary class to the ones from FlightClass class. In essence I am trying to retrieve data from two tables. If you take a look back at the FlightItenary class you will see like below that most of the attributes are from FlightItenary class and except from the classType attribute which is of the FlightClass class.
  1. Query q = em.createQuery("select p.departureDate, p.arrivalDate," +
  2. " p.departureAirport, p.arrivalAirport, p.flightNo, p.id from FlightItenary p, FlightClass a where p.id = a.flightId and cast(p.departureDate as string) = :depart" +
  3. " and lower(p.departureAirport)=:departure and lower(p.arrivalAirport)=:arrival and" +
  4. " a.classType=:classType and p.totalnum < 100 ");
My question now, is how do I retrieve this classType attribute as seen in the results.jsp page when it is not an attribute of FlightItenary because when I was looping throught the iterator I casted it.next() to an object of FlightItenary class.
This is the error I am getting anytime I run the results.jsp page

org.apache.jasper.JasperException: An exception occurred processing JSP page /results.jsp at line 101

  1. 98: <% List fl = (List) request.getAttribute("flightsDepart");
  2.  
  3. 99: //Iterator it = fl.iterator();
  4. 100: for (Iterator it = fl.iterator(); it.hasNext();) {
  5. 101: FlightItenary fli = (FlightItenary) it.next();
  6. 102: %>
  7. 103: <% String no = Integer.toString(num); %>
  8. 104: <tr>


  1. Stacktrace:
  2. org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
  3. org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
  4. org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
  5. org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
  6. javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  7. org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
  8. flight_search.Search.processRequest(Search.java:90)
  9. flight_search.Search.doPost(Search.java:121)
  10. javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
  11. javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  12. org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
  13.  
  14.  
  15. root cause
  16.  
  17. java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to flight_search.FlightItenary
  18. org.apache.jsp.results_jsp._jspService(results_jsp.java:155)
  19. org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
  20. javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  21. org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
  22. org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
  23. org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
  24. javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  25. org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
  26. flight_search.Search.processRequest(Search.java:90)
  27. flight_search.Search.doPost(Search.java:121)
  28. javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
  29. javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
  30. org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
  31.  
  32.  
  33. note The full stack trace of the root cause is available in the Apache Tomcat/6.0.18 logs.

Please if you have any idea of how i can resolve my problems please kindly reply to this post and if you know how I can retrieve the data from a list of hql query please help me about
Last edited by peter_budo; Dec 25th, 2008 at 5:07 am. Reason: Keep It Organized - For easy readability, always wrap programming code within posts in [code] (code blocks) and [icode] (inline code) tags.
Reply With Quote Quick reply to this message  
Join Date: Jun 2006
Posts: 7,649
Reputation: ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of ~s.o.s~ has much to be proud of 
Solved Threads: 474
Super Moderator
Featured Poster
~s.o.s~'s Avatar
~s.o.s~ ~s.o.s~ is offline Offline
Failure as a human

Re: problem with displaying data from hql query

 
0
  #2
Dec 26th, 2008
Simply put, the list returned by the `findFlights' method seems to return a list of Object arrays rather than a list of FlightItenary.

Don't mix and match type safe code with non-type safe code; either use generics all the way through or don't use it at all [not recommended]. Try to debug the `findFlights' to see what exactly is it returning.
I don't accept change; I don't deserve to live.

Jo Tujhe Jagaaye, Nindein Teri Udaaye Khwaab Hai Sachcha Wahi.
Nindon Mein Jo Aaye Jise To Bhul Jaaye Khawab Woh Sachcha Nahi.
Khwaab Ko Raag De, Nind Ko Aag De
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the JSP Forum
Thread Tools Search this Thread



Tag cloud for JSP
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC