• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

PROBLEM WITH DISPLAYING CONTENTS OF HQL QUERY

 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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:

package flight_search;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Query;
import javax.persistence.OneToMany;
import javax.persistence.Persistence;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
*
* @author ome
*/
@Entity
@Table(name = "flight_itenary")
@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 = epartureDate"), @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 = epartureAirport"), @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")})
public class FlightItenary implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "flight_no")
private String flightNo;
@Basic(optional = false)
@Column(name = "departure_date")
@Temporal(TemporalType.DATE)
private Date departureDate;
@Basic(optional = false)
@Column(name = "arrival_date")
@Temporal(TemporalType.DATE)
private Date arrivalDate;
@Basic(optional = false)
@Column(name = "departure_airport")
private String departureAirport;
@Basic(optional = false)
@Column(name = "arrival_airport")
private String arrivalAirport;
@Column(name = "totalnum")
private Integer totalnum;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "flightId")
private List<FlightClass> flightClassCollection;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "flightId")
private List<FlightPassengers> flightPassengersCollection;
static EntityManagerFactory emf = Persistence.createEntityManagerFactory("AirlinePU");


public FlightItenary() {
}

public FlightItenary(Integer id) {
this.id = id;
}

public FlightItenary(Integer id, String flightNo, Date departureDate, Date arrivalDate, String departureAirport, String arrivalAirport) {
this.id = id;
this.flightNo = flightNo;
this.departureDate = departureDate;
this.arrivalDate = arrivalDate;
this.departureAirport = departureAirport;
this.arrivalAirport = arrivalAirport;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFlightNo() {
return flightNo;
}

public void setFlightNo(String flightNo) {
this.flightNo = flightNo;
}

public Date getDepartureDate() {
return departureDate;
}

public void setDepartureDate(Date departureDate) {
this.departureDate = departureDate;
}

public Date getArrivalDate() {
return arrivalDate;
}

public void setArrivalDate(Date arrivalDate) {
this.arrivalDate = arrivalDate;
}

public String getDepartureAirport() {
return departureAirport;
}

public void setDepartureAirport(String departureAirport) {
this.departureAirport = departureAirport;
}

public String getArrivalAirport() {
return arrivalAirport;
}

public void setArrivalAirport(String arrivalAirport) {
this.arrivalAirport = arrivalAirport;
}

public Integer getTotalnum() {
return totalnum;
}

public void setTotalnum(Integer totalnum) {
this.totalnum = totalnum;
}

public List<FlightClass> getFlightClassCollection() {
return flightClassCollection;
}

public void setFlightClassCollection(List<FlightClass> flightClassCollection) {
this.flightClassCollection = flightClassCollection;
}

public List<FlightPassengers> getFlightPassengersCollection() {
return flightPassengersCollection;
}

public void setFlightPassengersCollection(List<FlightPassengers> flightPassengersCollection) {
this.flightPassengersCollection = flightPassengersCollection;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof FlightItenary)) {
return false;
}
FlightItenary other = (FlightItenary) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "flight_search.FlightItenary[id=" + id + "]";
}

public void persist(Object object) {
EntityManager em = emf.createEntityManager();
try {
em.getTransaction().begin();
em.persist(object);
em.getTransaction().commit();
} catch (Exception e) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
em.getTransaction().rollback();
} finally {
em.close();
}
}
public static List<FlightItenary> findFlights(String departure, String depart, String arrival, String classType) {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Query q = em.createQuery("select p.departureDate, p.arrivalDate," +
" p.departureAirport, p.arrivalAirport, p.flightNo, p.id from FlightItenary p, FlightClass a where p.id = a.flightId and cast(p.departureDate as string) = epart" +
" and lower(p.departureAirport)= eparture and lower(p.arrivalAirport)=:arrival and" +
" a.classType=:classType and p.totalnum < 100 ");
q.setParameter("depart", depart);
q.setParameter("arrival", arrival);
q.setParameter("departure", departure);
q.setParameter("classType", classType);
return q.getResultList();
/* Query q = em.createQuery("SELECT f FROM FlightItenary f");
return q.getResultList();*/
}
}
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.


package flight_search;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author ome
*/
public class Search extends HttpServlet {

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String departure = request.getParameter("departure").toLowerCase();
String arrival = request.getParameter("arrival").toLowerCase();
String comeback = request.getParameter("comeback");
String depart = request.getParameter("depart");
DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, Locale.UK);

String d = "";
String ret = "";
try {
Date dep = df.parse(depart);
// out.println(dep);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
d = dateFormat.format(dep);
//out.println(d);
}catch (ParseException e) {
out.println(e);
}

String country = request.getParameter("country").toLowerCase();
String classType = request.getParameter("classType").toLowerCase();
String num = request.getParameter("num");

if(request.getParameter("oneway")==null) {
List<FlightItenary> flights = FlightItenary.findFlights(departure, d, arrival, classType);

try {
Date re = df.parse(comeback);
//out.println(re);
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

ret = dateFormat.format(re);
//out.println(ret);
}catch (ParseException e) {
out.println(e);
}
String arr =arrival;
arrival = departure;
departure = arr;
List<FlightItenary> flightRet = FlightItenary.findFlights(departure, ret, arrival, classType);
//out.println(flights.size() + " " + flightRet.size());
if (flights.size() == 0 || flightRet.size()==0) {
request.setAttribute("flights", 0);
// forward request to JSP
String outputPage = "index.jsp";
RequestDispatcher rd = request.getRequestDispatcher(outputPage);
rd.forward(request, response);
}
else {
request.setAttribute("flightsDepart", flights);
request.setAttribute("flightsReturn", flightRet);
String outputPage = "results.jsp";
RequestDispatcher rd = request.getRequestDispatcher(outputPage);
rd.forward(request, response);
}

}

}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Returns a short description of the servlet.
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

}
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

<body>
<div class="main">

<div id="banner" style=" height: 100px; width: 600px; background: url(images/port.png) no-repeat;">
</div>
<div id="display">
<h1> TO </h1>
<table width="732" height="99" border="0" cellpadding="3" cellspacing="1">
<tr>
<td width="84" class="stylish">Depart</td>
<td width="102" class="stylish">Arrive</td>
<td width="127" class="stylish">From </td>
<td width="108" class="stylish">To</td>
<td width="102" class="stylish">Flight Number </td>
<td width="85" class="stylish">Class of Travel </td>
<td width="74" class="stylish">Select</td>
</tr>
<form name="list" id="list" action="" >
<% int num = 1; %>
<% List fl = (List) request.getAttribute("flightsDepart");
//Iterator it = fl.iterator();
for (Iterator it = fl.iterator(); it.hasNext() {
FlightItenary fli = (FlightItenary) it.next();
%>
<% String no = Integer.toString(num); %>
<tr>
<td class="text"><%out.print(fli.getDepartureDate());%></td>
<td class="text"><%out.print(fli.getArrivalDate());%></td>
<td class="text"><%out.print(fli.getDepartureAirport());%></td>
<td class="text"><%out.print(fli.getArrivalAirport());%></td>
<td class="text"><%out.print(fli.getFlightNo());%></td>
<td class="text"><%out.print(fli.getClassType());%></td>
<td class="text">
<input name="<% out.print("rad"+no);%>" type="radio" value="<%out.print(fli.getId());%>">
</td>
</tr>
<% } %>
</form>
</table>
</div>

</div>
</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.
Query q = em.createQuery("select p.departureDate, p.arrivalDate," +
" p.departureAirport, p.arrivalAirport, p.flightNo, p.id from FlightItenary p, FlightClass a where p.id = a.flightId and cast(p.departureDate as string) = epart" +
" and lower(p.departureAirport)= eparture and lower(p.arrivalAirport)=:arrival and" +
" 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

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


Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:505)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:416)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
flight_search.Search.processRequest(Search.java:90)
flight_search.Search.doPost(Search.java:121)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)


root cause

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to flight_search.FlightItenary
org.apache.jsp.results_jsp._jspService(results_jsp.java:155)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:342)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:267)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
flight_search.Search.processRequest(Search.java:90)
flight_search.Search.doPost(Search.java:121)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)


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
reply
    Bookmark Topic Watch Topic
  • New Topic